Django 4, ValueError: 'MyModel' instance needs to have a primary key value before this relationship can be used

257 Views Asked by At

The issue is a result from the update to django 4, in prior versions the issue was not present. When performing a reverse lookup on a foreign key relation, if the object being used for the reverse look up has not been save to the db (The object has no pk) an exception is raised, ValueError: 'MyModel' instance needs to have a primary key value before this relationship can be used. For example:

class Author(models.Model):
    name = models.CharField(max_length=100)
    biography = models.TextField()

class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)
    publication_date = models.DateField()

new_author = Author(name='John Doe', biography='A new author')
reverse_look_up = new_author.book_set.all()  # this raises the issue.

In django 3.2 and lower, performing this action wouldn't raise an error but rather return an empty queryset of book. You can solve this issue manually, by checking if the object has an id and then only performing the look up if it does, or by saving the object before hand, however I perform this kind of look up in numerous places and it would be difficult to do so. Would there be anyway to perform a generic fix for this, whether it be a change I can make to the model managers, monkey patching or project in general.

0

There are 0 best solutions below