On Jun 3, 11:40 am, derek <gamesb...@gmail.com> wrote: > I have a situation which is parallel to the following: > > class Building(models.Model): > id = models.AutoField(primary_key=True) > name = models.CharField(max_length=100) > def __unicode__(self): > return self.name > > class Manufacturer(models.Model): > name = models.CharField(max_length=100) > def __unicode__(self): > return self.name > > class Alarm(models.Model): > id = models.AutoField(primary_key=True) > name = models.CharField(max_length=100) > building = models.ForeignKey(Building) > master = models.BooleanField(default=0) > manufacturer = models.ForeignKey(Manufacturer) > def __unicode__(self): > return self.name > > Now I need to display a list of all buildings, along with any alarm > details, bearing in mind that not all buildings have alarms, while > some have more than one (but only one master). However, when > iterating through Buiding objects, a call to display > "alarm.manufacturer__name" gives me an "AttributeError: 'Building' > object has no attribute 'alarm'". Clearly, this is because, from the > building point of view, there is no known relationship to Alarm. > > How do I create such a relationship in Django, without changing the > database structure (e.g. creating an alarm field on Building, with a > one-to-many relationship to Alarm)? (and, ideally, also being able to > filter the result so only "master" alarms show up?) > > Thanks > Derek
You don't need to establish anything at all - you've already done all that is required. However, you've become a bit confused about how to do lookups. The 'double-underscore' syntax is *only* used within ORM method calls - eg .filter() and .get(). (It's actually a bit of a hack to allow dynamic parameters). Otherwise, you use the standard Python "." lookup. You should read this bit of the documentation on following relationships backwards: http://docs.djangoproject.com/en/dev/topics/db/queries/#following-relationships-backward So in your case, given a building, you can do this to get all its alarms: mybuilding.alarm_set.all() and this to get only its master ones: mybuilding.alarm_set.filter(master=True) Don't forget that in each case, the result is a queryset, not a single instance, even if only one result is returned. -- DR. -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.