atbug
atbug

Reputation: 838

A complex model query in django concerning related objects

Suppose I have the following two models:

class A(models.Model):
    name = models.CharField(max_length = 20)
    type = models.CharField(max_length = 20)
class B(models.Model):
    name = models.CharField(max_length = 20)
    type = models.CharField(max_length = 20)
    a = models.ForeinKey(A)

I want such A instances:

  1. Its name is 'name_a' and its type is 'type_a'
  2. It has at least one B objects related to it whose name is 'name_b' and whose type is 'type_b'

Is there a way to get such A instances at one time?

Upvotes: 0

Views: 29

Answers (1)

falsetru
falsetru

Reputation: 369074

You can use filter as follow:

A.objects.filter(name='name_a', type='type_a',
                 b__name='name_b', b__type='type_b').distinct()

UPDATE Added distinct to prevent duplicate objects.

Upvotes: 2

Related Questions