Home > front end >  Check if Many to Many exists in django?
Check if Many to Many exists in django?

Time:10-04

I have two models,

Model University:
      name = models.CharField(max_length=120)
Model Students:
      name = models.CharField(max_length=120)
      wishlist = models.ManyToManyField(University, blank=True)

Basically this is wishlist, user can add university to their wishlist and if the reclick on the heart icon i need to remove the wishlist:

Here is my code:

   student = request.user.student
   university = University.objects.get(id=pk)
   if university.student_set.exists():
       student.wishlist.remove(university)
   else:
       student.wishlist.add(university)

So when, user1 added university1 to wishlist, then user2 couldnt able to add university1 to the wishlist, i dont know where is the mistake !Pleas guide, any students can add any university to their wishlist (its the requirement)

I think the problem is with the if statment

CodePudding user response:

university.student_set.exists()

This doesn't check for any specific student. It should be:

university.student_set.filter(id=student.id).exists()

So overall this condition will be :

student = request.user.student
university = University.objects.get(id=pk)
if university.student_set.filter(id=student.id).exists():
   student.wishlist.remove(university)
else:
   student.wishlist.add(university)

CodePudding user response:

We can prevent fetching the related student of the user in case we want to remove the university from the wishlist. This is usually more safer since a User that has no related student will then not raise an error:

university = University.objects.get(id=pk)
if university.student_set.filter(user=request.user).exists():
    Student.wishlist.through.objects.filter(
        university=university,
        student__user=request.user
    ).delete()
else:
    request.user.student.wishlist.add(university)

We can slightly boost efficiency in the .remove(...) path by not fetching the .student of the user, and thus implement this as:

  • Related