Skip to main content
 首页 » 编程设计

python之如何在 Django 中过滤属性

2025年02月15日43leader

我目前在过滤数据时遇到问题。

型号

class Member(models.Model): 
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) 
    team_id = models.UUIDField(null=True) 
    username = models.CharField('', max_length=30) 
    is_active = models.BooleanField(default=False) 
 
    @property 
    def organization_id(self): 
        """This is to get the organization Id 
        """ 
        team = Team.objects.get(pk=self.team_id) 
        return team.organization_id 

现在我计划过滤所有 organation_id = 1 的成员。

这是我需要的:

memberList = Member.objects.filter(organization_id='1') 

所以我得到了这个错误:

Cannot resolve keyword 'organization_id' into field. Choices are: id, is_active, team_id, username 

如何使用 organization_id 过滤成员?

请您参考如下方法:

您的模型 Member 中没有任何名为 organization_id 的字段,这就是错误的原因。

相反你可能想要这个:

result_list = [] 
memberList = Member.objects.all() 
 
for item in memberList : 
    if item.organization_id() == '1' : 
        result_list.append(item) 
 
print result_list  

结果列表 result_list 将包含模型 Member 的所有必需对象。

谢谢。