Select related single object on reverse foreign key set

9 views
Skip to first unread message

M. Meent

unread,
Jan 18, 2017, 3:10:13 PM1/18/17
to Django users
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
Reply all
Reply to author
Forward
0 new messages