排除对ThroughModel中存在的对象的选择

时间:2018-10-17 17:25:16

标签: django django-models django-forms modelform

我有这三个模型和一个ModelForm。 就目前而言,我可以多次向电影添加同一个演员。

我正在寻找一种方法来防止这种情况的发生,方法是在CastingsForm人字段中输入查询集,如果该ID已经存在于电影中,则将排除对人的选择。

但是..我不知道怎么写。

class Person(models.Model):
    first_name = models.CharField(max_length=32)
    last_name = models.CharField(max_length=32)

class Movie(models.Model):
    title = models.CharField(max_length=128)
    director = models.ForeignKey(Person, on_delete=models.SET_NULL, null=True)
    screenplay = models.ForeignKey(Person, on_delete=models.SET_NULL, null=True)
    starring = models.ManyToManyField(Person, through='ThroughModel')

class ThroughModel(models.Model):
    person = models.ForeignKey(Person, on_delete=models.SET_NULL, null=True)
    movie = models.ForeignKey(Movie, on_delete=models.CASCADE)
    role = models.CharField(max_length=128, null=True)

和此表单

class CastingsForm(forms.ModelForm):
    role = forms.CharField(required=False)
    person = forms.ModelChoiceField(required=False)
    movie = forms.ModelChoiceField(Movie.objects.all(), required=False)

    class Meta:
        model = ThroughModel
        fields = ['role', 'person', 'movie']

0 个答案:

没有答案