0

This is the shape of my models.

class SomeModel(model):
    some_field = models.DateTimeField(blank=True, null=True)

class OtherModel(Model):
    list_of_some_models = models.ManyToManyField(SomeModel)

I have a dictionary like this, where each element in the list is the SomeModel pk:

{
    "list_of_some_models": [1, 10, 12, 20]
}

I would like to check if there is already a record that has a relationship with SomeModel of id 1, 10, 12 and 20.

is it possible?

Akira Kotsugai
  • 1,099
  • 3
  • 12
  • 19
  • try this `OtherModel.objects.filter(list_of_some_models__in=[1, 10, 12, 20])` – Vishal Singh Mar 09 '21 at 12:52
  • it returns 4 identical instances of OtherModel because I guess it finds 1 OtherModel for each pk in the list... I would like to find 1 OtherModel that simultaneously has relationship with all the 4 SomeModel – Akira Kotsugai Mar 09 '21 at 13:06
  • use `.distinct()` to remove the duplicates. – Vishal Singh Mar 09 '21 at 13:08
  • it does not work, because if I do OtherModel.objects.filter(list_of_some_models__in=[10]) it will find the OtherModel that has list_of_some_models = [1, 10, 12, 20] – Akira Kotsugai Mar 09 '21 at 14:10

1 Answers1

0

It is duplicate of Django queryset get exact manytomany lookup

this partially solves my problem, the issue is that if there are too many elements in the list_of_some_models the database complains about the number of joins.

Akira Kotsugai
  • 1,099
  • 3
  • 12
  • 19