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

10.2k views Asked by At

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?

3

There are 3 answers

0
Daniel Roseman On BEST ANSWER

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

0
Anchit Arnav On

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/

0
Matthew Cordaro On

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.