简体   繁体   中英

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.CharField(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.

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