Setting unique=True on a ForeignKey has the same effect as using a OneToOneField
Asked Answered
B

3

5

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:

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?

Briones answered 18/6, 2015 at 12:23 Comment(4)
I don't understand your question. The warning is giving you information.Hayes
warning != error. The OneToOne field already ensures the uniqueness.Exciter
I haven't unique option or OneToOneField! What is the warning denoting?Briones
Have a look at the source of the OneToOneField: github.com/django/django/blob/master/django/db/models/fields/…Exciter
H
4

primary_key implies unique=True. So, as the warning says, you should probably be using a OneToOneField.

Hayes answered 18/6, 2015 at 12:37 Comment(0)
H
3

As Daniel said you are probably better off using a OneToOneField.

A good explanation as to why this is can be found at this Stack Overflow Question.

Huehuebner answered 24/11, 2015 at 23:14 Comment(0)
L
0

In Short, Django is asking you is to replace your ForeignKey field with this:

author = models.OneToOneField(UserProfile, blank=False, primary_key=True)

Also, I shall suggest to add an on_delete key, and make it something like:

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/

Localize answered 7/9, 2021 at 18:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.