1

I have 3 Models (lets say A, B, C). Model C has both A and B as Foreign keys. Now I have primary_key of A and I want to retrieve the list of related B objects.

I want entire object of B not just fields which I can get using values() or values_list(). My Models are as below:

class A(models.Model):
    name = models.CharField(max_length=200)
    description = models.CharField(max_length=200)

class B(models.Model):
    name = models.CharField(max_length=200)
    description = models.CharField(max_length=200)

class C(models.Model):
    name = models.CharField(max_length=200)
    roll_number = models.IntegerField(default=0)
    a = models.ForeignKey(A,related_name='c_a')
    b = models.ForeignKey(A,related_name='c_b')
jagadeesh mn
  • 54
  • 2
  • 5

1 Answers1

1

You can slightly modify the answer from @Piyush S. Wanare like that:

c.objects.filter(a=primary_key_a).values('b')

Or if you only want a list with only b objects you can use values_list():

c.objects.filter(a=primary_key_a).values_list('b', flat=True)

This gives you a flat list of b (in this case). values returns a dictionary, values_list is similar but the output is a list of tuples instead of a dict. The additional option flat=True (works if only one one field is retrieved) returns a flat list of objects instead of a list of tuples of objects.

The docs for reference: