[Django]-Circular dependency in Django

4👍

You can use the name of the model (see docs), rather than the model object itself:

class Item(models.Model):      
    style = models.ForeignKey('app_name.Style')

1👍

If in an Item can be featured_item of only one style, then this means that the featured_item must be unique across the Style table.

What about:

class Style(models.Model):      
    featured_item = models.ForeignKey(Item, unique = True)

Which is then equivalent to doing:

class Style(models.Model):      
    featured_item = models.OneToOneField('Item', related_name = 'featured_in') # Style -> Item relationshio

class Item(models.Model):      
    style = models.ForeignKey(' Style') # Items -> Style relationship

Which gives you a backwards relationship for each Item telling you in which Style it is featured, in addition to the forward relationship that tells you which style it belongs to.

I guess you will probably want to use a limit_choices_to clause so that an Item can only be featured in a Style it is part of.

Leave a comment