查询集多对多 'ManyRelatedManager' 对象不可迭代

Queryset Many to many 'ManyRelatedManager' object is not iterable

我正在使用表单来过滤多对多关系的选择,以仅显示查询集之后的关系。这是我的表单的样子

class ContractAdminForm(forms.ModelForm):
    class Meta:
      model = Contract
      fields = '__all__'

    def __init__(self, *args, **kwargs):
        super(ContractAdminForm, self).__init__(*args, **kwargs)
        self.fields['client_year_periods'].queryset =ClientYearPeriod.objects.filter(
              Q(contract_id__isnull=True) | Q(contract_id=self.instance.id) &
              Q(client__in=self.instance.client_entity.all()))

错误:'ManyRelatedManager'对象不可迭代 问题是由 Q(client__in=self.instance.client_entity))

我需要使用连接到 Client Ops 的客户法律模型来过滤模型年份。

在这里查看它是如何构建的

型号

class ClientEntity(models.Model):
    name = models.CharField(max_length=350, verbose_name='Client Name')
    countries = models.ManyToManyField(Country, blank=True)
    operations_code = models.ManyToManyField(Client)

class ClientYearPeriod(models.Model):
    client = models.ForeignKey(Client, on_delete=models.PROTECT, null=True)
    [...]

class Contract (models.Model):
   client_entity= models.ManyToManyField(ClientLegal)
   client_year_periods = models.ManyToManyField(ClientYearPeriod, blank=True)
   [...]


class Client(models.Model):
    code = models.CharField(max_length=3, verbose_name='Client Code')
    name = models.CharField(max_length=250, unique=True)
   

预期结果

这个合约选择了客户Someone

在客户端实体模型中它与Client = BEM相关

这里应该只显示客户:BEM 保存后(不是在创建合约时,因为上面选择的客户还没有保存)

client__in=… 期望 QuerySetself.instance.client_entity 是经理,而不是 QuerySet

但是你需要制作 QuerySetClient,所以:

class ContractAdminForm(forms.ModelForm):
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['client_year_periods'].queryset = ClientYearPeriod.objects.filter(
            Q(contract_id__isnull=True) |
            Q(contract_id=self.instance.id) &
            Q(client__in=Client.objects.<b>filter(cliententity__contract=self.instance).distinct()</b>)
        )
    
    class Meta:
        model = Contract
        fields = '__all__'