Reputation: 620
I have the following models:
class ModelOne(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
class ModelTwo(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
is_visible = models.BooleanField(default=False)
modelones = models.ManyToManyField(ModelOne, blank=True)
In a view, I want to get a queryset of ModelOne
s based on attributes of ModelTwo
. For instance, how might I get a queryset of ModelOne
s that have a ModelTwo
with is_visible
set to True
referencing them?
To provide an example:
one_one = ModelOne.objects.create()
one_two = ModelOne.objects.create()
two_one = ModelTwo.objects.create()
two_two = ModelTwo.objects.create(is_visible=True)
two_three = ModelTwo.objects.create()
two_two.modelones.add(one_one)
two_two.save()
two_three.modelones.add(one_two)
two_three.save()
queryset = [????]
queryset
would only contain one_one
because two_two
has a reference to one_one
and also has is_visible
True
.
Upvotes: 1
Views: 128
Reputation: 476528
You filter with:
ModelOne.filter(modeltwo__is_visible=True)
You can filter relations in reverse. It will use the related_query_name=…
parameter [Django-doc] to use in the .filter(…)
[Django-doc]. If you did not specify that, it will use the related_name=…
parameter [Django-doc], and if you did not specify any of the two, it uses the name of the class in lowercase.
Upvotes: 1