[Django]-Django models.py Circular Foreign Key

45👍

You don’t actually have a circular reference; the issue is that, at the time you define Album, you haven’t defined Image yet. You can fix that by using a string instead:

class Album(models.model):
  thumb = models.ForeignKey('Image', null=True, blank=True)

However, in this case, you might want to use a OneToOneField instead of a foreign key. (Note that you’ll still have to use the trick with the string, though).

👤mipadi

13👍

Use quotes to force a lazy reference:

models.ForeignKey('Image', null=True, blank=True)

Also, ForeignKey.related_name is your friend (avoids back-reference name clashes).

0👍

This is old but anyway, i’d like to say that I don’t see a reason for attribute album in model Image. In my opinion, it is not really needed.

👤clime

Leave a comment