与其他外键选择相关的外键

时间:2016-09-22 14:15:09

标签: python django foreign-key-relationship

我正在尝试在django中制作以下模型:

class Client(models.Model):
    client = models.CharField(max_length=200)
    loyal = models.BooleanField(default=False)

class Contact(models.Model):
    first_name = models.CharField(max_length=200)
    last_name = models.CharField(max_length=200)
    client_id = models.ForeignKey(Client, on_delete=models.SET_NULL,null=True)

class Activity(models.Model):
    title = models.CharField(max_length=30)
    text = models.CharField(max_length=1000)
    client_id = models.ForeignKey(Client, on_delete=models.PROTECT)
    contact_id = models.ForeignKey(Contact, on_delete=models.PROTECT,limit_choices_to={'id__in': client_id.contact_set.all().values('id').query})

我想要实现的目标 - 当我创建一个活动并在其中选择客户端时 - 我希望在联系人字段中我只能从与选择客户相关的联系人中选择,因为当我这样做时:

contact_id = models.ForeignKey(Contact, on_delete=models.PROTECT)

Django允许我从所有联系人中进行选择。我想以某种方式限制我需要选择的联系人列表,我尝试这样:

contact_id = models.ForeignKey(Contact, on_delete=models.PROTECT,limit_choices_to={'id__in': client_id.contact_set.all().values('id').query})

但是我收到了这个错误:

AttributeError: 'ForeignKey' object has no attribute 'contact_set'

我该怎么做?

0 个答案:

没有答案