Skip to content
Advertisement

Two dependent conditions in exclude DJANGO

I want to check whether the current user already has the same movie id in his personal list or not. If he has it then I want to exclude that movie from my trending list.

I want it to be something like this.

views.py

trending = list(Movies.objects.exclude(mid in mymovies WHERE uid = request.user.id))

models.py

class Movies(models.Model):
    mid = models.CharField(max_length=255, primary_key=True)
    title = models.CharField(max_length=255, null=True, blank=True)
    rating = models.CharField(max_length=5, null=True, blank=True)
    type = models.CharField(max_length=255, null=True, blank=True)
    genre = models.CharField(max_length=255, null=True, blank=True)
    rdate = models.CharField(max_length=255, null=True, blank=True)
    language = models.CharField(max_length=255, null=True, blank=True)
    cover = models.CharField(max_length=255, null=True, blank=True)
    description = models.TextField(null=True, blank=True)
    sequal = models.CharField(max_length=255, null=True, blank=True)
    trailer = models.CharField(max_length=255, null=True, blank=True)
    year = models.CharField(max_length=5, null=True, blank=True)
    objects = models.Manager()
    
    def __str__(self) -> str:
        return self.title   

class MyMovies(models.Model):
    mid = models.ForeignKey(Movies, on_delete=CASCADE)
    uid = models.ForeignKey(User, on_delete=CASCADE, null=True, blank=True)
    watched = models.BooleanField()
    date = models.DateTimeField(auto_now_add=True)
    objects = models.Manager()   
    

Advertisement

Answer

You can .exclude(…) with:

trending = Movies.objects.exclude(mymovies__uid=request.user)

If you specified a related_query_name=… [Django-doc] or a related_name=… [Django-doc], then you need to use that to make a JOIN with your Movies model:

trending = Movies.objects.exclude(related_name_of_fk__uid=request.user)

Note: normally a Django model is given a singular name, so MyMovie instead of MyMovies.


Note: Normally one does not add a suffix _id to a ForeignKey field, since Django will automatically add a “twin” field with an _id suffix. Therefore it should be user, instead of uid.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement