pythondjangodjango-modelsdjango-model-fielddjango-constraints

Unique together between field and model connected by ForeignKey django


I have two models.

class Post(models.Model):
    title = models.CharField(max_length=150)

class Attachment(models.Model):
    type = models.CharField(choices=AttachmentChoices.get_choices(), max_length=15)
    link = models.URLField()
    post = models.ForeignKey('Post', on_delete=models.PROTECT, related_name='attachments')

I want to do something like this in meta class of Post model

    class Meta:
        unique_together = [('title', 'attachments')]

but it dosn't work couse django can't find attachments field. Is there a solution provided by django that can solve this problem.


Solution

  • You can use UniqueConstraint and also try to create a many-to-many relationship between Post and Attachment models using attachments field, try the following:

    from django.db.models import UniqueConstraint
    
    class Post(models.Model):
        title = models.CharField(max_length=150)
        attachments = models.ManyToManyField('Attachment', related_name='posts')
    
        class Meta:
            constraints = [
                UniqueConstraint(fields=['title'], name='unique_title_with_attachments')
            ]
    

    Now, will create a unique constraint on the combination of title and attachments fields. This means that when you create a new Post instance, Django will check if there is already a Post instance with the same title and attachments combination, and if so, it will raise a ValidationError.