Constraints across foreign keys

15 views
Skip to first unread message

Rich Rauenzahn

unread,
Dec 4, 2017, 3:02:32 PM12/4/17
to Django users

Let's say I have:

class Restaurant(Model):
   pass

class Table(Model)
   restaurant = ForeignKey(Restaurant)

class Chair(Model)
   restaurant = ForeignKey(Restaurant)
   table = ForeignKey(Table)

Is there a best practice for ensuring that the chair assigned to a table is always from the same restaurant?  These models above assume that we might have spare chairs not yet assigned to tables.

My actual case is more like this:

class A(Model):
   pass

class B(Model):
   a = ForeignKey(A)

class C(Model):
   a = ForeignKey(A)

class D(Model):
   b = ForeignKey(B)
   c = ForeignKey(C)

And I want to ensure b.a == c.a.

(I think I just have to manually add db sql constraints in my migrations and also override save())

Are there any well supported / used django packages to manage this for me?  This https://github.com/rapilabs/django-db-constraints looks promising, but is awfully quiet.

Rich


Reply all
Reply to author
Forward
0 new messages