这是我的模型。最好的方法是什么? 一对一字段允许始终只创建一个评论。
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']