我有 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()
到目前为止,我只能将位置字段设为空白。不知道下一步该去哪里,因为我看到的例子与我的不完全一样。