Home > Software design >  How to update through model in django many to many?
How to update through model in django many to many?

Time:11-03

class Blog():
  likes = models.ManyToManyField(User, through="myapp.Like")

class Like():
  user = models.ForeignKey(Like)
  blog = models.ForeignKey(Blog)
  liked_at = models.DateTimeField(auto_now_add=True)
  some_bool_field = models.BooleanField(default=False)

Now in views:

 def like_blog(request, id):
     blog = Blog.objects.get(id=id)
     blog.users.add(request.user)
     # now how can I update some_bool_field and How can I make use of this field 

In future I can use some query like blog.users.filter(some_bool_field=False) so for that case I want to update this field.

OR AM I MISSING THE USES OF THROUGH MODEL ?

CodePudding user response:

If you want to update the through model objects you can do like so:

def like_blog(request, id):
     blog = Blog.objects.get(id=id)
     blog.users.add(request.user)
     # query your through model
     Like.objects.filter(user=request.user, blog=blog).update(some_bool_field=True)

Getting all blogs filtered likes with some_bool_field=True:

true_boolean_likes = Blog.objects.filter(likes__some_bool_field=True)

CodePudding user response:

for through model update you can use bellow method to update

like = Blog.objects.get(id=id)
for like in Likes.objects.filter(likes__some_bool_field =False): #or true by what you want to filter
    like.the_field_want_to_update.update(id=like.id)

here .update update the value by which you are filtering here with id so it will update what data passed to it.

  • Related