独特的外键与Django对 [英] Unique foreign key pairs with Django

查看:122
本文介绍了独特的外键与Django对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三种型号:产品用户评论

审查与产品和用户相关联如下:

A review is linked to a product and a user as follows:

class Review(models.Model):
    product = models.ForeignKey(Product)    
    user = models.ForeignKey(User)
    review_text = models.TextField()
    creation_date = models.DateTimeField(auto_now_add=True)

我想允许每个用户每个产品只提交一个评论。推荐的方法是什么?通过模型,通过验证,还是别的什么?我对Django / Python很新谢谢。

I'd like to allow each user to submit only one review per product. What is the recommended way to achieve this? Through the model, through verification, or something else? I'm very new to Django/Python. Thanks.

推荐答案

使用 unique_together ,以确保每个用户/产品组合是唯一的:

Use unique_together to make sure that each user/product combination is unique:

class Review(models.Model):

  class Meta:

    unique_together = ['user', 'product']

  user = models.ForeignKey(User)
  product = models.ForeignKey(Product)

这篇关于独特的外键与Django对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆