I have the problem with Category Model. I have 2 tables:
class Category(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=30, null=False) class Movie(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=30, null=False)
so they are standard models with categories. User can create Category by creating a movie with the name of category additionaly. The problem is when user is trying to create Movie with category name that already exists, because it will create another category with the same name (like duplicate) and I want to avoid it.
How to do it? I can’t create unique name field, because many users can have same category (but I can use ManyToManyRelation) but still I don’t know how to automatically avoid duplicates like bellow:
- If Category with that Name and this User does not exist > create Category
- If Category with that Name and this User exists > use this Category
Regards
Advertisement
Answer
Though your explanation is vague. But from your explanation, it seems like you want the categories to be unique with each user. Different users can have same categories, but same user can’t have any duplicate one.
for that
class Category(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=30, null=False) class Meta: unique_together = ["user","name"] #This will #make a constraint to check if both user and name is unique
According to your comment you want unique constraints with nullable ForeignKey too. try overriding the clean method in the model class (Category model)
from django.core.exceptions import ValidationError def clean(self): if self.user is None and Category.objects.filter(name=self.name, user=None).exists(): raise ValidationError("Duplicate Category with name=%s already exists" % self.name)