不应该Member
有外键Group
吗?您希望一个组中有很多成员,而不是一个成员的多个组,对吗?
class Member(models.Model):
name = models.CharField(max_length=100)
dob = models.DateField()
group = modes.ForeignKey('Group', related_name='members')
class Group(models.Model):
name = models.CharField(max_length=100)
owner = models.ForeignKey('Member', related_name='owned_groups')
class Activity(models.Model):
group = models.ForeignKey('Group', related_name='activities')
topic = models.CharField(max_length=100)
start_by = models.ForeignKey('Member', related_name='started_activities')
participants = models.ManyToManyField('Member', related_name='participating_activities')
然后你可以这样做:
class ActivityForm(ModelForm):
def __init__(self, *args, **kwargs):
super(ActivityForm, self).__init__(*args, **kwargs)
if 'initial' in kwargs:
self.fields['participants'].queryset = Member.objects.filter(group=initial.group)
class Meta:
model = Activity
编辑
随着使用 a 的更改,ManyToManyField
我建议您也修复您的字段名称和相关名称。在开发过程的早期进行更改比在遇到无法修复的不同问题时更容易。如果它更容易理解,请这样想:相关名称将可在ForeignKey
orManyToManyField
指向的模型上访问,并且将包含queryset
具有 0 个或更多条目的 a。
所以如果你有...
class Member(models.Model):
name = models.CharField(max_length=100)
dob = models.DateField()
class Group(models.Model):
name = models.CharField(max_length=100)
owner = models.ForeignKey('Member', related_name='owned_groups')
members = models.ManyToManyField('Member', related_name='groups')
class Activity(models.Model):
group = models.ForeignKey(Group)
topic = models.CharField(max_length=100)
start_by = models.ForeignKey('Member', related_name='started_activities')
participants = models.ManyToManyField('Member', related_name='activities')
然后你可以做类似的事情......
g1 = Group.objects.create(name='Group 1', ...)
g2 = Group.objects.create(name='Group 2', ...)
member = Member.objects.get(name='John')
member.groups.all() # Get all the groups for the member
member.groups.add(g1, g2) # Add the member to 2 groups
member.activities.all() # Get all activities the member is a participant in
member.started_activities.all() # Get all activities started by the user
还有你的表格...
class ActivityForm(ModelForm):
...
def __init__(self, *args, **kwargs):
super(ActivityForm, self).__init__(*args, **kwargs)
if 'initial' in kwargs:
self.fields['participants'].queryset = initial.group.members.all()
class Meta:
model = Activity
我认为这会起作用,但如果不是:
class ActivityForm(ModelForm):
...
def __init__(self, *args, **kwargs):
super(ActivityForm, self).__init__(*args, **kwargs)
if 'initial' in kwargs:
self.fields['participants'].queryset = Member.objects.filter(group__id=initial.group.id)
class Meta:
model = Activity