Django Python在哪里添加辅助函数来避免代码重复?

2024-10-01 15:40:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我来自土生土长的POO编程语言,我是Python的新手,也是Django。你知道吗

我看到在Django他们把一个应用程序的所有代码放在同一个地方视图.py或者型号.py. 你知道吗

现在我在一个叫做:

def create_ticket(self):
    ....

里面有密码

        is_staff=User.objects.get(pk=request.user.id).is_staff
    if is_staff==1:
        R_Client_Accountant = LinkUserContable.objects.filter(contable=mongoId)
        print(R_Client_Accountant)
        accountantList = []
        for relation in R_Client_Accountant:
            try:
                rmongosql = RMongoSql.objects.get(mongoId=relation.user.id)
                user = User.objects.get(pk=rmongosql.helpdeskId)
                accountantList.append((user.id,user.username))
            except:
                pass
    else:
        R_Client_Accountant = LinkUserContable.objects.filter(user=mongoId)
        accountantList = []
        for relation in R_Client_Accountant:
            try:
                rmongosql = RMongoSql.objects.get(mongoId=relation.contable.id)
                user = User.objects.get(pk=rmongosql.helpdeskId)
                accountantList.append((user.id,user.username))
            except:
                pass

如您所见,我在“try”中重复代码,只是交换{user XOR contable} 如果我想写一个传递参数this{user XOR contable}的函数,我应该把它放在哪里?你知道吗

对我来说,在相应的模型中型号.py不正确,因为有太多代码行引用不同的模型和视图.py只是为了查看函数,对吗?你知道吗

谨致问候, 维克托。你知道吗


Tags: 代码pyclientidgetobjectsisstaff
1条回答
网友
1楼 · 发布于 2024-10-01 15:40:33

可以使用getattr函数使用字符串来获取所需的属性getattr(relation, relation_attr)

你的函数应该是这样的

def create_ticket(self):
    is_staff=User.objects.get(pk=request.user.id).is_staff
    if is_staff==1:
        relation_attr = 'user'
    else:
        relation_attr = 'contable'
    R_Client_Accountant = LinkUserContable.objects.filter(contable=mongoId)
    print(R_Client_Accountant)
    accountantList = []
    for relation in R_Client_Accountant:
        try:
            rmongosql = RMongoSql.objects.get(mongoId=getattr(relation, relation_attr).id)
            user = User.objects.get(pk=rmongosql.helpdeskId)
            accountantList.append((user.id, user.username))
        except:
            pass

相关问题 更多 >

    热门问题