[Fixed]-Django how to make address model unique – based on house and postcode/zipcode


What you need is to add a unique constraint for a pair building, postcode.
In django it can be achieved via unique_together https://docs.djangoproject.com/en/1.8/ref/models/options/#unique-together

class Meta:
    unique_together = ("building", "postcode")

Then what you really need is not a get_or_create but update_or_create method.

address, created = Address.objects.update_or_create(
    postcode=postcode, building=building, defaults=defaults)

Leave a comment