[英]Setting unique=True on a ForeignKey has the same effect as using a OneToOneField
I switched to Django 1.8.2 from 1.7 recently, but I encounter with a little bit issues, for example in one of my models I have:我最近从 1.7 切换到 Django 1.8.2,但我遇到了一些问题,例如在我的一个模型中:
class Author(models.Model):
author = models.ForeignKey(UserProfile, blank=False, primary_key=True)
timestamp = models.DateTimeField(auto_now_add=True)
But when I run server I come across with this following warning:但是当我运行服务器时,我遇到了以下警告:
WARNINGS:
exam.Author.author: (fields.W342) Setting unique=True on a ForeignKey has the same effect as using a OneToOneField.
HINT: ForeignKey(unique=True) is usually better served by a OneToOneField.
What should I do?我该怎么办?
primary_key
implies unique=True
. primary_key
表示unique=True
。 So, as the warning says, you should probably be using a OneToOneField. 所以,正如警告所说,你可能应该使用OneToOneField。
As Daniel said you are probably better off using a OneToOneField
. 正如丹尼尔所说 ,使用OneToOneField
可能会更好。
A good explanation as to why this is can be found at this Stack Overflow Question . 关于为什么会这样的一个很好的解释可以在这个Stack Overflow问题中找到 。
In Short, Django is asking you is to replace your ForeignKey field with this:简而言之,Django 要求您将 ForeignKey 字段替换为:
author = models.OneToOneField(UserProfile, blank=False, primary_key=True)
Also, I shall suggest to add an on_delete key, and make it something like:另外,我建议添加一个on_delete键,并使其类似于:
author = models.OneToOneField(UserProfile, blank=False, primary_key=True, on_delete=models.CASCADE)
Reference: https://docs.djangoproject.com/en/3.2/topics/db/examples/one_to_one/参考: https : //docs.djangoproject.com/en/3.2/topics/db/examples/one_to_one/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.