How to create a unique constraint for a associated model, transaction management

I have two models:

class DesiredTenant(models.Model):

    id = models.CharField("System-ID", primary_key=True, max_length=63, unique=True,


class Domain(models.Model):
    system = models.ForeignKey(DesiredTenant, on_delete=models.CASCADE)
    domain = models.CharField(max_length=200, unique=True)
    primary_domain = models.BooleanField("Primary Domain", default=False)

I am using django-admin to interactively create a new tenant in my user-interface.
The user defines the “id” in the user interface and adds a new domain as a (django.contrib.admin.) StackedInline.

I would like to add a constraint that only allows one domain to be the primary_domain for a specific tenant (ideally selected by a radio button in the StackedInline).

Is that possible? How can i implement that?

I suppose i have two problems:

  • how can i achieve the radio button selection in the StackedInlines
  • how can i define a suitable constraint?
  • how can i build a transactional context in the database (postgresql) for all Domain objects associated to the tenant to prevent constraint violations? (by default django executes the save() method independently for every domain)

This is one of those situations where I think you’ll really be better off writing your own form and view to process it. It’s likely to be a lot easier than trying to make this work within the admin.

From the docs for The Django admin site:

If you need to provide a more process-centric interface that abstracts away the implementation details of database tables and fields, then it’s probably time to write your own views.