Search Results

Search found 448 results on 18 pages for 'foreignkey'.

Page 6/18 | < Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >

  • Proper way to add record to many to many relationship in Django

    - by blcArmadillo
    First off, I'm planning on running my project on google app engine so I'm using djangoappengine which as far as I know doesn't support django's ManyToManyField type. Because of this I've setup my models like this: from django.db import models from django.contrib.auth.models import User class Group(models.Model): name = models.CharField(max_length=200) class UserGroup(models.Model): user = models.ForeignKey(User) group = models.ForeignKey(Group) On a page I have a form field where people can enter a group name. I want the results from this form field to create a UserGroup object for the user - group combination and if the group doesn't yet exist create a new Group object. At first I started putting this logic in the UserGroup class with a add_group method but quickly realized that it doesn't really make sense to put this in the UserGroup class. What would the proper way of doing this be? I saw some stuff about model managers. Is this what those are for?

    Read the article

  • django modelformset - one form per related table row

    - by Toby
    Hello, I have two models: class Model1(): name = CharField() url = CharField() class Model2(): model1 = ForeignKey(Model1) user = ForeignKey(User) zzz = CharField() There are 5 rows for model1 in the database, these are fixed and will rarely change. I need to display a formset for model2 that allows users to enter the zzz value, the formset must always show one form per row in the model1 table, the label for each form in the formset must be the name of the related model1. If the user deletes a model2 in the formset the next time the page loads it will render an empty zzz value for that form and the user must be able to edit the previous zzz value - meaning it must be pre populated with all model2 rows associated with the user. The idea is to print each row in the model1 table as a form instead of the user selecting the related model1 name in a select box. I know its not that complicated, but I'm seriously stumped and keep going round in circles!! Many thanks in advance. Similar to http://stackoverflow.com/questions/298779/form-or-formset-to-handle-multiple-table-rows-in-django

    Read the article

  • Django data migration when changing a field to ManyToMany

    - by Ken H
    I have a Django application in which I want to change a field from a ForeignKey to a ManyToManyField. I want to preserve my old data. What is the simplest/best process to follow for this? If it matters, I use sqlite3 as my database back-end. If my summary of the problem isn't clear, here is an example. Say I have two models: class Author(models.Model): author = models.CharField(max_length=100) class Book(models.Model): author = models.ForeignKey(Author) title = models.CharField(max_length=100) Say I have a lot of data in my database. Now, I want to change the Book model as follows: class Book(models.Model): author = models.ManyToManyField(Author) title = models.CharField(max_length=100) I don't want to "lose" all my prior data. What is the best/simplest way to accomplish this? Ken

    Read the article

  • Django JSON serializable error

    - by Hulk
    With the following code below, There is an error saying File "/home/user/web_pro/info/views.py", line 184, in headerview, raise TypeError("%r is not JSON serializable" % (o,)) TypeError: <lastname: jerry> is not JSON serializable In the models code header(models.Model): firstname = models.ForeignKey(Firstname) lastname = models.ForeignKey(Lastname) In the views code headerview(request): header = header.objects.filter(created_by=my_id).order_by(order_by)[offset:limit] l_array = [] l_array_obj = [] for obj in header: l_array_obj = [obj.title, obj.lastname ,obj.firstname ] l_array.append(l_array_obj) dictionary_l.update({'Data': l_array}) ; return HttpResponse(simplejson.dumps(dictionary_l), mimetype='application/javascript') what is this error and how to resolve this? thanks..

    Read the article

  • Django Forms, Foreign Key and Initial retuen all associated values

    - by gramware
    I a working with Django forms. The issue I have is that Foreign Key fields and those using initial take all associated entries (all records associated with that record other then the one entry i wanted e.g instead of getting a primary key, i get the primary key, post subject, post body and all other values attributed with that record). The form and the other associated queries still work well, but this behaviour is clogging my database. How do i get the specific field i want instead of all records. An example of my models is here: A form field for childParentId returns postID, postSubject and postBody instead of postID alone. Also form = ForumCommentForm(initial = {'postSubject':forum.objects.get(postID = postID), }) returns all records related to postID. class forum(models.Model): postID = models.AutoField(primary_key=True) postSubject = models.CharField(max_length=25) postBody = models.TextField() postPoster = models.ForeignKey(UserProfile) postDate = models.DateTimeField(auto_now_add=True) child = models.BooleanField() childParentId = models.ForeignKey('self',blank=True, null=True) deleted = models.BooleanField() def __unicode__(self): return u'%s %s %s %s %s' % (self.postSubject, self.postBody, self.postPoster, self.postDate, self.postID

    Read the article

  • Sumproduct using Django's aggregation

    - by Matthew Rankin
    Question Is it possible using Django's aggregation capabilities to calculate a sumproduct? Background I am modeling an invoice, which can contain multiple items. The many-to-many relationship between the Invoice and Item models is handled through the InvoiceItem intermediary table. The total amount of the invoice—amount_invoiced—is calculated by summing the product of unit_price and quantity for each item on a given invoice. Below is the code that I'm currently using to accomplish this, but I was wondering if there is a better way to handle this using Django's aggregation capabilities. Current Code class Item(models.Model): item_num = models.SlugField(unique=True) description = models.CharField(blank=True, max_length=100) class InvoiceItem(models.Model): item = models.ForeignKey(Item) invoice = models.ForeignKey('Invoice') unit_price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.DecimalField(max_digits=10, decimal_places=4) class Invoice(models.Model): invoice_num = models.SlugField(max_length=25) invoice_items = models.ManyToManyField(Item,through='InvoiceItem') def _get_amount_invoiced(self): invoice_items = self.invoiceitem_set.all() amount_invoiced = 0 for invoice_item in invoice_items: amount_invoiced += (invoice_item.unit_price * invoice_item.quantity) return amount_invoiced amount_invoiced = property(_get_amount_invoiced)

    Read the article

  • Django Forms, Foreign Key and Initial return all associated values

    - by gramware
    I a working with Django forms. The issue I have is that Foreign Key fields and those using initial take all associated entries (all records associated with that record other then the one entry i wanted e.g instead of getting a primary key, i get the primary key, post subject, post body and all other values attributed with that record). The form and the other associated queries still work well, but this behaviour is clogging my database. How do i get the specific field i want instead of all records. An example of my models is here: A form field for childParentId returns postID, postSubject and postBody instead of postID alone. Also form = ForumCommentForm(initial = {'postSubject':forum.objects.get(postID = postID), }) returns all records related to postID. class forum(models.Model): postID = models.AutoField(primary_key=True) postSubject = models.CharField(max_length=25) postBody = models.TextField() postPoster = models.ForeignKey(UserProfile) postDate = models.DateTimeField(auto_now_add=True) child = models.BooleanField() childParentId = models.ForeignKey('self',blank=True, null=True) deleted = models.BooleanField() def __unicode__(self): return u'%s %s %s %s %s' % (self.postSubject, self.postBody, self.postPoster, self.postDate, self.postID

    Read the article

  • django ManyToMany through help

    - by dotty
    Hay I've got a question about relationships. I want to Users to have Friendships. So a User can be a friend with another User. I'm assuming i'll need to use the ManyToManyField, through a Friendship table. But i cannot get it to work. Any ideas? Here are my models. class User(models.Model): username = models.CharField(max_length=999) password = models.CharField(max_length=999) created_on = models.DateField(auto_now = False, auto_now_add = True) updated_on = models.DateField(auto_now = True, auto_now_add = False) friends = models.ManyToManyField('User', through='Friendship') class Friendship(models.Model): user = models.ForeignKey('User') friend = models.ForeignKey('User') Thanks

    Read the article

  • Django foreign key question

    - by Hulk
    All, i have the following model defined, class header(models.Model): title = models.CharField(max_length = 255) created_by = models.CharField(max_length = 255) def __unicode__(self): return self.id() class criteria(models.Model): details = models.CharField(max_length = 255) headerid = models.ForeignKey(header) def __unicode__(self): return self.id() class options(models.Model): opt_details = models.CharField(max_length = 255) headerid = models.ForeignKey(header) def __unicode__(self): return self.id() AND IN MY VIEWS I HAVE p= header(title=name,created_by=id) p.save() Now the data will be saved to header table .My question is that for this id generated in header table how will save the data to criteria and options table..Please let me know.. Thanks..

    Read the article

  • How to customize a many-to-many inline model in django admin

    - by Jonathan
    I'm using the admin interface to view invoices and products. To make things easy, I've set the products as inline to invoices, so I will see the related products in the invoice's form. As you can see I'm using a many-to-many relationship. In models.py: class Product(models.Model): name = models.TextField() price = models.DecimalField(max_digits=10,decimal_places=2) class Invoice(models.Model): company = models.ForeignKey(Company) customer = models.ForeignKey(Customer) products = models.ManyToManyField(Product) In admin.py: class ProductInline(admin.StackedInline): model = Invoice.products.through class InvoiceAdmin(admin.ModelAdmin): inlines = [FilteredApartmentInline,] admin.site.register(Product, ProductAdmin) The problem is that django presents the products as a table of drop down menus (one per associated product). Each drop down contains all the products listed. So if I have 5000 products and 300 are associated with a certain invoice, django actually loads 300x5000 product names. Also the table is not aesthetic. How can I change it so that it'll just display the product's name in the inline table? Which form should I override, and how?

    Read the article

  • Reorganizing many to many relationships in Django

    - by Galen
    I have a many to many relationship in my models and i'm trying to reorganize it on one of my pages. My site has videos. On each video's page i'm trying to list the actors that are in that video with links to each time they are in the video(the links will skip to that part of the video) Here's an illustration Flash Video embedded here Actors... Ted smith: 1:25, 5:30 jon jones: 5:00, 2:00 Here are the pertinent parts of my models class Video(models.Model): actor = models.ManyToManyField( Actor, through='Actor_Video' ) # more stuff removed class Actor_Video(models.Model): actor = models.ForeignKey( Actor ) video = models.ForeignKey( Video) time = models.IntegerField() Here's what my Actor_Video table looks like, maybe it will be easier to see what im doing id actor_id video_id time (in seconds) 1 1 3 34 2 1 3 90 i feel like i have to reorganize the info in my view, but i cant figure it out. It doesn't seem to be possible in the template using djangos orm. I've tried a couple things with creating dictionaries/lists but i've had no luck. Any help is appreciated. Thanks.

    Read the article

  • Django shows too many warnings when deleting an object

    - by valya
    Hello! I have two models: class Account(models.Model): main_request = models.ForeignKey('JournalistRequest', related_name='main_request') key = models.CharField(_('Key'), max_length=100) class JournalistRequest(models.Model): account = models.ForeignKey(Account, blank=True, null=True) When I try to delete a JournalistRequest, It shows warning with a lot of nesting, like Are you sure you want to delete the selected ?????? ??? objects? All of the following objects and their related items will be deleted: Journalist Request: some request Account: some account Journalist Request: some request Account: some account Journalist Request: some request Account: some account Journalist Request: some request Account: some account Journalist Request: some request All accounts are the same one (ids are same), and all requests are the same one, so I think it becaues of a recursion. But I have no idea how to solve this problem in Django 1.1.1! Can you help me?

    Read the article

  • Select a subset of foreign key elements in inlineformset_factory in Django

    - by Enis Afgan
    Hello, I have a model with two foreign keys: class Model1(models.Model): model_a = models.ForeignKey(ModelA) model_b = models.ForeignKey(ModelB) value = models.IntegerField() Then, I create an inline formset class, like so: an_inline_formset = inlineformset_factory(ModelA, Model1, fk_name="model_a") and then instantiate it, like so: a_formset = an_inline_formset(request.POST, instance=model_A_object) Once this formset gets rendered in a template/page, there is ChoiceField associated with the model_b field. The problem I'm having is that the elements in the resulting drop down menu include all of the elements found in ModelB table. I need to select a subset of those based on some criteria from ModelB. At the same time, I need to keep the reference to the instance of model_A_object when instantiating inlineformset_factory and, therefore, I can't just use this example. Any suggestions?

    Read the article

  • Django models avaoid duplicates

    - by Hulk
    In models, class Getdata(models.Model): title = models.CharField(max_length=255) state = models.CharField(max_length=2, choices=STATE, default="0") name = models.ForeignKey(School) created_by = models.ForeignKey(profile) def __unicode__(self): return self.id() In templates <form> <input type="submit" save the data/> </form> If the user clicks on the save button and the above data is saved in the table how to avoid the duplicates,i.e, if the user again clicks on the same submit button there should not be another entry for the same values.Or is it some this that has to be handeled in views Thanks..

    Read the article

  • Django models avoid duplicates

    - by Hulk
    In models, class Getdata(models.Model): title = models.CharField(max_length=255) state = models.CharField(max_length=2, choices=STATE, default="0") name = models.ForeignKey(School) created_by = models.ForeignKey(profile) def __unicode__(self): return self.id() In templates <form> <input type="submit" save the data/> </form> If the user clicks on the save button and the above data is saved in the table how to avoid the duplicates,i.e, if the user again clicks on the same submit button there should not be another entry for the same values.Or is it some this that has to be handeled in views Thanks..

    Read the article

  • ValueError with multi-table inheritance in Django Admin

    - by jorde
    I created two new classes which inherit model Entry: class Entry(models.Model): LANGUAGE_CHOICES = settings.LANGUAGES language = models.CharField(max_length=2, verbose_name=_('Comment language'), choices=LANGUAGE_CHOICES) user = models.ForeignKey(User) country = models.ForeignKey(Country, null=True, blank=True) created = models.DateTimeField(auto_now=True) class Comment(Entry): comment = models.CharField(max_length=2000, blank=True, verbose_name=_('Comment in English')) class Discount(Entry): discount = models.CharField(max_length=2000, blank=True, verbose_name=_('Comment in English')) coupon = models.CharField(max_length=2000, blank=True, verbose_name=_('Coupon code if needed')) After adding these new models to admin via admin.site.register I'm getting ValueError when trying to create a comment or a discount via admin. Adding entries works fine. Error msg: ValueError at /admin/reviews/discount/add/ Cannot assign "''": "Discount.discount" must be a "Discount" instance. Request Method: GET Request URL: http://127.0.0.1:8000/admin/reviews/discount/add/ Exception Type: ValueError Exception Value: Cannot assign "''": "Discount.discount" must be a "Discount" instance. Exception Location: /Library/Python/2.6/site-packages/django/db/models/fields/related.py in set, line 211 Python Executable: /usr/bin/python Python Version: 2.6.1

    Read the article

  • SQL Alchemy related Objects Error

    - by alex
    from sqlalchemy.orm import relation, backref from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey, Date, Sequence from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class GUI_SCENARIO(Base): __tablename__ = 'GUI_SCENARIO' Scenario_ID = Column(Integer, primary_key=True) Definition_Date = Column(Date) guiScenarioDefinition = relation('GUI_SCENARIO_DEFINITION', order_by='GUI_SCENARIO_DEFINITION.Scenario_Definition_ID', backref='guiScenario') def __init__(self, Scenario_ID=None, Definition_Date=None): self.Scenario_ID = Scenario_ID self.Definition_Date = Definition_Date class GUI_SCENARIO_DEFINITION(Base): __tablename__='GUI_SCENARIO_DEFINITION' Scenario_Definition_ID = Column(Integer, Sequence('Scenario_Definition_ID_SEQ'), primary_key=True) Scenario_FK = Column(Integer, ForeignKey('GUI_SCENARIO.Scenario_ID')) Definition_Date=Column(Date) guiScenario = relation(GUI_SCENARIO, backref=backref('guiScenarioDefinition', order_by=Scenario_Definition_ID)) def __init__(self, Scenario_FK, Definition_Date): self.Scenario_FK = Scenario_FK self.Definition_Date = Definition_Date guiScenario = relation(GUI_SCENARIO, backref=backref('guiScenarioDefinition', order_by=Scenario_Definition_ID)) tableNameScenario = "GUI_SCENARIO" scenarioClass = getattr(MappingTablesScenario, tableNameScenario) tableScenario = Table(tableNameScenario, meta, autoload=True) mapper(scenarioClass, tableScenario) scenarioName = scenarioDefinition.name scenarioDefinitionDate = datetime.today() newScenario = MappingTablesScenario.GUI_SCENARIO(scenarioName, scenarioDefinitionDate) print newScenario.guiScenarioDefinition If I try to get the objects related to a scenarioObject, I always get this error: AttributeError: 'GUI_SCENARIO' object has no attribute 'guiScenarioDefinition' Does anyone know, why I get this error?

    Read the article

  • Annotate and Aggregate function in django

    - by thesteve
    In django I have the following tables and am trying to count the number of votes by item. class Votes(models.Model): user = models.ForeignKey(User) item = models.ForeignKey(Item) class Item(models.Model): name = models.CharField() description = models.TextField() I have the following queryset queryset = Votes.objects.values('item__name').annotate(Count('item')) that returns a list with item name and view count but not the item object. How can I set it up so that the object is returned instead of just the string value? I have been messing around with Manager and Queryset methods, that the right track? Any advice would be appreciated.

    Read the article

  • Django syncdb not making tables for my app

    - by Rosarch
    It used to work, and now it doesn't. python manage.py syncdb no longer makes tables for my app. From settings.py: INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'mysite.myapp', 'django.contrib.admin', ) What could I be doing wrong? The break appeared to coincide with editing this model in models.py, but that could be total coincidence. I commented out the lines I changed, and it still doesn't work. class MyUser(models.Model): user = models.ForeignKey(User, unique=True) takingReqSets = models.ManyToManyField(RequirementSet, blank=True) takingTerms = models.ManyToManyField(Term, blank=True) takingCourses = models.ManyToManyField(Course, through=TakingCourse, blank=True) school = models.ForeignKey(School) # minCreditsPerTerm = models.IntegerField(blank=True) # maxCreditsPerTerm = models.IntegerField(blank=True) # optimalCreditsPerTerm = models.IntegerField(blank=True) UPDATE: When I run python manage.py loadddata initial_data, it gives an error: DeserializationError: Invalid model identifier: myapp.SomeModel Loading this data had worked fine before. This error is thrown on the very first data object in the data file.

    Read the article

  • Django admin causes high load for one model...

    - by Joe
    In my Django admin, when I try to view/edit objects from one particular model class the memory usage and CPU rockets up and I have to restart the server. I can view the list of objects fine, but the problem comes when I click on one of the objects. Other models are fine. Working with the object in code (i.e. creating and displaying) is ok, the problem only arises when I try to view an object with the admin interface. The class isn't even particularly exotic: class Comment(models.Model): user = models.ForeignKey(User) thing = models.ForeignKey(Thing) date = models.DateTimeField(auto_now_add=True) content = models.TextField(blank=True, null=True) approved = models.BooleanField(default=True) class Meta: ordering = ['-date'] Any ideas? I'm stumped. The only reason I could think of might be that the thing is quite a large object (a few kb), but as I understand it, it wouldn't get loaded until it was needed (correct?).

    Read the article

  • How to specify an association relation using declarative base

    - by sam
    I have been trying to create an association relation between two tables, intake and module . Each intake has a one-to-many relationship with the modules. However there is a coursework assigned to each module, and each coursework has a duedate which is unique to each intake. I tried this but it didnt work: intake_modules_table = Table('tg_intakemodules',metadata, Column('intake_id',Integer,ForeignKey('tg_intake.intake_id', onupdate="CASCADE",ondelete="CASCADE")), Column('module_id',Integer,ForeignKey('tg_module.module_id', onupdate ="CASCADE",ondelete="CASCADE")), Column('dueddate', Unicode(16)) ) class Intake(DeclarativeBase): __tablename__ = 'tg_intake' #{ Columns intake_id = Column(Integer, autoincrement=True, primary_key=True) code = Column(Unicode(16)) commencement = Column(DateTime) completion = Column(DateTime) #{ Special methods def __repr__(self): return '"%s"' %self.code def __unicode__(self): return self.code #} class Module(DeclarativeBase): __tablename__ ='tg_module' #{ Columns module_id = Column(Integer, autoincrement=True, primary_key=True) code = Column(Unicode(16)) title = Column(Unicode(30)) #{ relations intakes = relation('Intake', secondary=intake_modules_table, backref='modules') #{ Special methods def __repr__(self): return '"%s"'%self.title def __unicode__(self): return '"%s"'%self.title #} When I do this the column duedate specified in the intake_module_table is not created. Please some help will be appreciated here. thanks in advance

    Read the article

  • Sqlalchemy+elixir: How query with a ManyToMany relationship?

    - by Hugo
    Hi, I'm using sqlalchemy with Elixir and have some troubles trying to make a query.. I have 2 entities, Customer and CustomerList, with a many to many relationship. customer_lists_customers_table = Table('customer_lists_customers', metadata, Column('id', Integer, primary_key=True), Column('customer_list_id', Integer, ForeignKey("customer_lists.id")), Column('customer_id', Integer, ForeignKey("customers.id"))) class Customer(Entity): [...] customer_lists = ManyToMany('CustomerList', table=customer_lists_customers_table) class CustomerList(Entity): [...] customers = ManyToMany('Customer', table=customer_lists_customers_table) I'm tryng to find CustomerList with some customer: customer = [...] CustomerList.query.filter_by(customers.contains(customer)).all() But I get the error: NameError: global name 'customers' is not defined customers seems to be unrelated to the entity fields, there's an special query form to work with relationships (or ManyToMany relationships)? Thanks

    Read the article

  • group inlines in django admin

    - by pablo
    Hi I have a two models, Model1 and Model2. Model2 has a FK to Model1 and FK to iteself. In the admin I show Model2 as inlines in Model1 change_form. I want to modify the way the inlines are shown in the admin. I need to group all the instances that have the same parent_model2 and display them as a readonly field with a string of 'childs' in the parent Model2 instance. I know how to use itertools.groupby (or the django version) but don't know how to do it in the admin. What should I override to be able to iterate over all the Model2 instances, group them by parent, add children to the parent and remove children from the inlines? class Model1(models.Model): name = models.CharField() class Model2(models.Model): name = models.CharField() fk_model1 = models.ForeignKey('self', blank=True, null=True) parent_model2 = models.ForeignKey('self', blank=True, null=True) Thanks

    Read the article

  • Joining different models in Django

    - by Andrew Roberts
    Let's say I have this data model: class Workflow(models.Model): ... class Command(models.Model): workflow = models.ForeignKey(Workflow) ... class Job(models.Model): command = models.ForeignKey(Command) ... Suppose somewhere I want to loop through all the Workflow objects, and for each workflow I want to loop through its Commands, and for each Command I want to loop through each Job. Is there a way to structure this with a single query? That is, I'd like Workflow.objects.all() to join in its dependent models, so I get a collection that has dependent objects already cached, so workflows[0].command_set.get() doesn't produce an additional query. Is this possible?

    Read the article

  • Django Grouping Query

    - by Matt
    I have the following (simplified) models: class Donation(models.Model): entry_date = models.DateTimeField() class Category(models.Model): name = models.CharField() class Item(models.Model): donation = models.ForeignKey(Donation) category = models.ForeignKey(Category) I'm trying to display the total number of items, per category, grouped by the donation year. I've tried this: Donation.objects.extra(select={'year': "django_date_trunc('year', %s.entry_date)" % Donation._meta.db_table}).values('year', 'item__category__name').annotate(items=Sum('item__quantity')) But I get a Field Error on item__category__name. I've also tried: Item.objects.extra(select={"year": "django_date_trunc('year', entry_date)"}, tables=["donations_donation"]).values("year", "category__name").annotate(items=Sum("quantity")).order_by() Which generally gets me what I want, but the item quantity count is multiplied by the number of donation records. Any ideas? Basically I want to display this: 2010 - Category 1: 10 items - Category 2: 17 items 2009 - Category 1: 5 items - Category 3: 8 items

    Read the article

< Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >