0

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Add distinct() to prevent duplicate objects.
@KevinChristopherHenry, Thank you for advice. I updated the answer to include that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.