简体   繁体   中英

Two foreign keys referencing each other in Django

I have an Order model. I want to track each order's current state and which states it has been through.

Can I use

class Order(models.Model):
    current_state = models.ForeignKey('State')

class State(models.Model):
    order = models.ForeignKey(Order)

or is it better to use

class Order(models.Model):
    pass

class State(models.Model):
    order = models.ForeignKey(Order)
    is_current = models.BooleanField(default=True)

I don't know if it's bad practice to have two foreign keys referencing each other.

These are not "two foreign keys referencing each other" - which wouldn't mean anything - but "two models referencing each other".

There's no "better" solution here, depends on your exact specs and needs, but as a general rule, the simpler your model the better. If the "current" state is garanteed to always be the last one (you may want to have a created_on timestamp in your State model FWIW), then you don't need the Order.current_state FK nor even the is_current flag.

Also if you go for the Order.current_state FK, you'll have to make it nullable, else you'll have a chicken-and-egg problem...

Oh and yes: this is definitly not a Django or Python question, it' a relational model design problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM