Friday, June 1, 2012

Obtaining objects from a many-to-many relationship

I've got two models with one having a many-to-many relationship with the
other:

class A(models.Model):
name = models.CharField("name")

class B(models.Model):
haveone = models.ManyToManyField(A)

What is the idiom for getting all instances of A which are referenced in
B? I found this works:

A.objects.annotate(n=models.Count('b')).filter(n__gt=0)

But istm that there is probably a more concise and straightforward way
to accomplish this (and the solution is probably obvious but it is
escaping me). tia

- Tom

--
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 django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate