[Answered ]-Django IntegrityError Duplicate entry on Foreignkey

2👍

First of all, right expression to check for existence is:

existing = Relation.objects.filter(actor=actor, target=target).exists()

But the djano way to write your sentences is with get_or_create method, is that method that you are looking for:

Relation.objects.get_or_create(actor=actor, target=target, 
                                 defaults={ 'status':status }
                              )

Or, for your case, something like:

r, _ = Relation.objects.get_or_create(actor=actor, target=target )
r.status = '' if r.status == 'on' else status
r.save()

Leave a comment