如何从相同模型(相同对象)的两个字段(列)形成查询集?

时间:2019-08-12 22:19:34

标签: python sql django django-models django-queryset

我正在尝试形成查询集以加载到选择表单中。该查询集的值来自另一个模型中相同模型(相同对象)的2个字段。

例如,我在数据库中存储了一个Slug = 1sunariatl的GameId(object)。此游戏ID具有GameId.home = ari和GameId.visitor = atl。我想创建一个具有选择字段(驱动)的新表单(PlayForm),该表单允许用户在主队和客队之间进行选择。 (表单中的选择字段将显示“ atl”和“ ari”)

如何基于同一对象的这些特定字段值形成新的查询集?

models.py

class GameId(models.Model):

    week = models.CharField(max_length = 100)
    day = models.CharField(max_length = 100)
    home = models.ForeignKey(Team, on_delete=models.SET_NULL, null = True, related_name='home')
    visitor = models.ForeignKey(Team, on_delete=models.SET_NULL, null = True, related_name='visitor')

class Play(models.Model):
    driving = models.CharField(max_length = 100)

forms.py

class GameIdForm(forms.ModelForm):
    class Meta:
        model = GameId
        fields = [
            'day', 'week','home', 'visitor'
        ]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['home'].queryset = Team.objects.all()

class PlayForm(forms.ModelForm):
    def __init__(self, round_list, *args, **kwargs):
        super(PlayForm, self).__init__(*args, **kwargs)
        self.fields['driving'].queryset = #insert code here

    class Meta:
        model = Play
        fields = [
            'driving'
        ]

0 个答案:

没有答案