Rahul Sharma
Rahul Sharma

Reputation: 2495

Query a queryset from a django Foreign key connected model

I have a model like the following:

class Flow(models.Model):

    flow_type_choices = (('Static', 'Static'), ('Transit', 'Transit'), ('Circuit', 'Circuit'), ('Close', 'Close'))

    flow_name = models.CharField(max_length=500, default=0)
    flow_info = models.CharField(max_length=500, default=0)

    flow_type = models.CharField(max_length=500, default=0, choices=flow_type_choices)
    flow_days = models.IntegerField(default=0)
    sender_client = models.ForeignKey(Client, on_delete=models.CASCADE)
    receiver_client = models.ForeignKey(ReceiverClient, on_delete=models.CASCADE)

I am trying to get the queryset of receiver_client attached to a particular sender client

For this I have tried the following:

         items = list(Flow.objects.filter(sender_client=request.user.pk).
                 values_list('receiver_client', flat=True).distinct())
    print("items", items)
    rc = ReceiverClient.objects.filter(pk__in = items)

and I am getting :

items <QuerySet [11, 8, 7, 18, 4, 6, 3]>

How can I get the queryset of the receiver clients instead of the pk ?

Upvotes: 0

Views: 38

Answers (1)

Iain Shelvington
Iain Shelvington

Reputation: 32244

You can get this data in a single query by following the relationship all the way from ReceiverClient to Client

ReceiverClient.objects.filter(flow__sender_client=client)

Upvotes: 4

Related Questions