0

我有 2 个表“客户端”和“位置”。

class Client(models.Model):
    name = models.CharField(max_length=50)

class Location(models.Model):
    name = models.CharField(max_length=50)

一个客户端可以在多个位置,一个位置可以有多个客户端。

我创建了第三个表来保存这种关系:

class Client_Location(models.Model):
    client = models.ForeignKey(Client, on_delete=models.CASCADE)
    location = models.ForeignKey(Location, on_delete=models.CASCADE)

我创建了一个表单来测试我是否可以使下拉列表动态化,所以如果我要选择一个客户端,那么任何链接到该客户端的位置都只会出现。

class ClientLocationForm(forms.ModelForm):
    class Meta:
        model = Client_Location
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['location'].queryset = Location.objects.none()

到目前为止,我只能将位置字段设为空白。不知道下一步该去哪里,因为我看到的例子与我的不完全一样。

4

1 回答 1

0

只需对代码进行最少的更改,您就可以将现有Client_Location模型添加through为新的显式ManyToMany关系的模型。为此,请将以下字段添加到您的Client模型中:

 locations = models.ManyToManyField('Location', through='Client_Location', related_name='clients')

如果您需要完全动态更新,您需要编写一个视图,该视图提供指定客户端 ( client.locations.all()) 的位置列表,然后将它们显示在您的页面上。

于 2019-01-15T17:39:11.607 回答