Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Circular Model Dependency

I have a circular dependency in my Django models, such that model A has a foreign key reference to B, while B has a many-to-many reference to A. I've consulted other SO posts and have used the string model names instead of the actual classes, but to no avail. Here are abbreviated versions of my two classes:

User model

import listings.models

class User(models.Model):
    ...
    favorites = models.ManyToManyField('listings.models.Listing')

Listing model

import users.models

class Listing(models.Model):
    ...
    owner = models.ForeignKey('users.models.User')

Every time I attempt to run syncdb, it outputs the following error:

Error: One or more models did not validate: users.user: 'favorites' has an m2m relation with model listings.models.Listing, which has either not been installed or is abstract. listings.listing: 'owner' has a relation with model users.models.User, which has either not been installed or is abstract.

How do I resolve this without sacrificing the established relationship?

like image 219
Zach Avatar asked Nov 25 '12 18:11

Zach


1 Answers

  • 'listings.models.Listing' should be 'listings.Listing'
  • 'users.models.User' should be 'users.User' (or 'auth.User' if you were to use django.contrib.auth.models.User)

Refer to official documentation for more.

like image 183
jpic Avatar answered Sep 28 '22 15:09

jpic