我应该在模型中创建什么关系,以便一个用户只能为产品创建一个注释?



这是我的模型。最好的方法是什么? 一对一字段允许始终只创建一个评论。

class Person(models.Model):
first_name = models.CharField(
max_length=512,
blank=True,
null=True,
)
last_name = models.CharField(
max_length=512,
blank=True,
null=True,
)
class Product(models.Model):
slug = SlugField()
name = NameField()
description = DescriptionField()
class Comment(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
person = models.OneToOneField(Person, on_delete=models.CASCADE)
text = models.TextField(null=True, blank=True)
# You can use 'unique_together' feature of model
class Product(models.Model):
slug = SlugField()
name = NameField()
description = DescriptionField()
class Comment(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
person = models.ForeignKey(Person, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
text = models.TextField(null=True, blank=True)

class Meta:
unique_together = ("person", "product")

您想要的是每个用户多个评论,每个产品多个评论。但是,您需要确保评论中用户和产品的唯一性。这可以使用unique_together来实现(见 https://docs.djangoproject.com/en/2.2/ref/models/options/#unique-together(:

class Comment(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
person = models.ForeignKey(Person, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
text = models.TextField(null=True, blank=True)
class Meta:
unique_together = ['person', 'product']

我相信您还需要向Comment添加Product

class Comment(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
person = models.ForeignKey(Person, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
text = models.TextField(null=True, blank=True)
class Meta:
unique_together = ['person', 'product']

相关内容

  • 没有找到相关文章

最新更新