Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a django QuerySet of all ForeignKeys of all objects in a Queryset

I have a model (or actually 2 models, but the other is not that relevant)

class Foo(models.Model):
    ...
    bar = models.ForeignKey(Bar,
        ...
    )

When I have a QuerySet of Foo:s, how do I get all the Bar instances that are referenced by that QuerySet?

Since I'm using MySQL, I can't do .distinct(['bar'])

like image 611
Kimvais Avatar asked Sep 26 '12 11:09

Kimvais


People also ask

How do you get or view all the items in a model in Django?

The simplest way you can get the list of objects of an attribute is to first get a query-set of that attribute alone using values_list then converting the django query-set to a python set using set() and finally to a list using list() .

How do I get QuerySet in Django?

You get a QuerySet by using your model's Manager . Each model has at least one Manager , and it's called objects by default. Access it directly via the model class, like so: >>> Blog.objects <django.db.models.manager.Manager object at ...> >>> b = Blog(name='Foo', tagline='Bar') >>> b.objects Traceback: ...

What does objects all () return in Django?

all() Returns a copy of the current QuerySet (or QuerySet subclass). This can be useful in situations where you might want to pass in either a model manager or a QuerySet and do further filtering on the result. After calling all() on either object, you'll definitely have a QuerySet to work with.

How do I get the size of a QuerySet in Django?

If the QuerySet only exists to count the amount of rows, use count(). If the QuerySet is used elsewhere, i.e. in a loop, use len() or |length. Using count() here would issue another SELECT-query to count the rows, while len() simply counts the amount of cached results in the QuerySet.


1 Answers

foo_queryset = Foo.objects.filter(attr=value)
referenced_bars = Bar.objects.filter(id__in=foo_queryset.values('bar_id'))
like image 67
Iain Shelvington Avatar answered Oct 03 '22 01:10

Iain Shelvington