On 10/31/07, George Vilches <[EMAIL PROTECTED]> wrote: [snip] Here is what I want to count: > > "All the quantity of items necessary to complete all the selected > assemblies". > > That's not thinking in SQL, that's very much thinking about the objects > at hand. I have Assemblies, and I need to know the total number of > Items. That's a concept that can be thought about strictly from the > objects. > > So, if I have two assemblies, and Assembly 1 connects to 2 items, and > Assembly 2 connects to 3 items, I want the total result of 5 when I do a > count() where I refer to the Items (select_related()).
A ForeignKey in the Assembly model (as you have it now) is not the right way to describe the relationship you state in the above sentence. A ForeignKey is used to describe a many-to-one relationship, where the "many" side is the model containing the ForeignKey and the "one" side is the model that is the target of the ForeignKey. That is, many Assembly instances might "point to" the same Item instance, but each individual Assembly is associated with exactly one Item. So a single Item would have a set of Assembly objects "connected" to it, not vice-versa. This happens naturally by default because the ForeignKey uses the primary key field of the target model. You've overridden that by specifying a to_field whose value is not unique (allowing that may be a bug in Django). I think this is the crux of what's causing the differences you see in the various ways of determining count() -- Django is assuming a unique relationship which in you case does not exist. Now, as to fixing it for your case, I'm not sure how to do it because I'm not clear on the relationship between Assembly and Item. Is it many-to-one (only reversed from the way currently defined in your models) or many-to-many? If it really is many-to-one, then moving the ForeignKey field over into the Item model may be all you need to do (plus turning around your thinking, which often trips me up when trying to work out ForeignKey relationships). Karen --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~----------~----~----~----~------~----~------~--~---