class Favorite(models.Model): user = models.ForeignKey(User, ondelete=models.CASCADE)…
- User
class Favorite(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) company = models.ForeignKey(Company, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) updated_at = models.DateTimeField(auto_now= True, blank=True, null=True)
class Meta: verbose_name = "Favorite" verbose_name_plural = "Favorites"make a use to not use the same company two time. Django restframework
- Assistant
To ensure that a user cannot favorite the same company twice, you can add a unique constraint to the
Favoritemodel that combines theuserandcompanyfields.Here's one way to do it:
class Favorite(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) company = models.ForeignKey(Company, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) updated_at = models.DateTimeField(auto_now=True, blank=True, null=True) class Meta: verbose_name = "Favorite" verbose_name_plural = "Favorites" unique_together = ('user', 'company')The
unique_togetherattribute specifies a tuple of field names that must be unique together. In this case, we're saying that each(user, company)pair should be unique.With this constraint in place, if a user tries to create a
Favoriteobject with the sameuserandcompanyvalues as an existing object, Django will raise adjango.db.IntegrityErrorand prevent the creation of the duplicate object. To handle this error gracefully in a Django REST Framework view, you could catch the and return a validation error response to the client.