Ömer Alkin
Ömer Alkin

Reputation: 303

Django filter many to many model's JSON field with the given

I have Movies and Participants model and it is like this,

class Movie(models.Model):
    something something
    participants = models.ManyToManyField(Participant)

class Participant(models.Model):
    something something 
    type = models.CharField(max_length=127, null=True, blank=True)

What I would like to do is, check the Participants type field with the given list and according to it list the Movies or not.

For example, I have type_list=["Adults", "Children", "Senior"] but Movie object has 2 Participant objects and one of them is type="Adults" and the other one is type="Children"

In example I would expect not to show that Movies since it doesn't have all the required Participants type.

What have I tried so far;

however, this returns a two participants object

this one also returns the two participant object.

I also cant use the & operator.

The only idea I left with is to check the count of the participants. Query returned two but I have three participant so I can't show this movie but the problem is in here list is variable that coming from front end. So my both query and if statement should be generic and I don't know how to do both and also I am %100 sure that there should be a best practice rather than this.

I would appreciate every tiny help, thank you!

Upvotes: 0

Views: 116

Answers (1)

neverwalkaloner
neverwalkaloner

Reputation: 47354

You can fetch all particiant's types using values_list with distinct and compare returned value with provided type_list by iterating over provided list:

types_from_db = movie.participants.values_list("type", flat=True).distinct()

for movie_type in ["Adults", "Children", "Senior"]:
     if movie_type not in types_from_db:
         return False
return True 

Upvotes: 1

Related Questions