Wednesday, January 18, 2017

Select related single object on reverse foreign key set

Hi,

I have the following structure:

    class A(models.Model):
        date = DateField(nullable=True)
        ...
   
    class B(models.Model):
        a = ForeignKey(A)
        a_date_is_null_at_creation = BooleanField()
        ...

I select the following data this way: (an O(n) operation for n A)

    a = A.objects.get(id=1)
    relevant_b = a.b_set.get(is_start=(a.date==None))

, which is similar to

    A.objects.get(id=1).prefetch_related(b_set)

, and constructs 2 queries.

Can I construct a queryset which selects the relevant B row inline with the A query, such that only one query is executed?
there is always only one result for B.is_start == (B.a.date == Null)

Thanks in advance,

-M Meent

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/2d637986-eb67-473e-8c4e-a58e8031973d%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment