Django: UnboundLocalError: local variable 'company' referenced before assignment

谁说我不能喝 提交于 2019-12-02 05:19:00

In your function, you assign to a variable named company, so Python considers company to be a local variable, but at that moment unassigned, so you will need to use anoter variable name to avoid this:

def get_object(self):
    pk1 = self.kwargs['pk1']
    pk2 = self.kwargs['pk2']
    # make sure the variable name is different than the model name
    company_obj = get_object_or_404(company, pk=pk1)
    group1 = get_object_or_404(group1, pk=pk2)
    return group1

Since you here however do not use company_obj, you might want to drop the variable name:

def get_object(self):
    pk1 = self.kwargs['pk1']
    pk2 = self.kwargs['pk2']
    get_object_or_404(company, pk=pk1)
    group1 = get_object_or_404(group1, pk=pk2)
    return group1

as an alternative, if your group1 is "related" to company, and you want to chekck if that holds, it makes sense to filter on that company:

def get_object(self):
    pk1 = self.kwargs['pk1']
    pk2 = self.kwargs['pk2']
    company_obj = get_object_or_404(company, pk=pk1)
    group1 = get_object_or_404(group1, pk=pk2, company=company_obj)
    return group1

Note: PEP-8 [Python-doc] advices class names to be written in CamelCase, whereas fields and local variables are written in lower_case. It is not uncommon to see something like some_class = SomeClass(), so because the camel case starts with an uppercase, clashes between local variables and classes, will never exist.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!