Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - create or delete object

Tags:

django

I am wondering what is the best way of creating (if it doesn't exist) or deleting (if it does exist) an object in Django.

I know I can do something like this:

if Like.objects.filter(user=request.user, post=post).exists():
    Like.objects.filter(user=request.user, post=post).delete()
else:
    Like.objects.create(user=request.user, post=post)

Is there a better way, like for instance the get_or_create method that Django provides?

like image 653
Dalvtor Avatar asked Mar 06 '23 21:03

Dalvtor


1 Answers

If it's a single object do this:

try:
    Like.objects.get(user=request.user, post=post).delete()
except Like.DoesNotExist
    Like.objects.create(...)
like image 131
aliva Avatar answered Mar 17 '23 16:03

aliva