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?
If it's a single object do this:
try:
Like.objects.get(user=request.user, post=post).delete()
except Like.DoesNotExist
Like.objects.create(...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With