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.
You can use
UniqueConstraintand also try to create a many-to-many relationship betweenPostandAttachmentmodels usingattachmentsfield, try the following:Now, django will create a unique constraint on the combination of
titleandattachmentsfields. This means that when you create a newPostinstance, Django will check if there is already aPostinstance with the sametitleandattachmentscombination, and if so, it will raise aValidationError.