How to Create Dependent Model Relationship in Django
I am trying to create a Django model for the following scenario:
There are several Clubs. Each Club has a single leader and several members. The leader is also a member.
These are my models so far:
class Club(models.Model):
name = models.CharField(max_length=50)
leader = models.ForeignKey('Member', related_name='+')
class Member(models.Model):
name = models.Char开发者_JS百科Field(max_length=50)
club = models.ForeignKey(Club)
In the admin interface, I can't add a member without first making a club, but I can't make a club without creating a member to designate as the leader. I tried adding Blank=True to the leader ForeignKey relationship, but it still doesn't work.
How should I create the models for the situation?
Thanks in advance!
Create a ClubLeader model class, with columns as Foreign Keys to a Club and a Member to be the leader. Enforce uniqueness for Club+Member ids in that table to make sure you dont have multiple leaders. Remove 'leader' from your Club class.
Also, I wouldn't join any club that would have someone like me for a member (Groucho Marx)
For further information, Blank=True doesn't mean that the field in the database can be null. It only means that a form field can be blank when using a ModelForm (Or perhaps just the admin - either/or). What you want is a blank=True, null=True
. That allows a null value, and a blank value in the form/admin panel.
I would still go with Spacedman's answer though. Provide a separate table that sits 'inbetween'. This way, you enforce that Members must belong to a club.
精彩评论