来自另一位经理的Django ORM呼叫管理器方法?

时间:2013-11-21 18:09:07

标签: python django

有关如何从Manager.py中访问其他管理器方法的任何提示?

无论我做什么,我似乎无法访问我的其他经理的方法。 Python抱怨它没有被定义......

如果我在managers.py中导入模型会导致问题吗?通知包括或其他什么?

managers.py:

# Returns the whole family who are active
def get_active_dependents_including_guardian( self, consumer, connectedOnly = False ):
    logger.debug('get_active_dependents_including_guardian')
    results = self.model.objects.filter( guardian = consumer,
                                      is_active = True ).order_by('dob')

    if connectedOnly:
        from myir import models
        #OPTIMIZE: this can be optimized if I query for all patient ids for each dependent in one trip.  But I don't even know how to do this yet cause I'm a noob.
        results = [d for d in results if models.DependentPatientID.objects.get_patient_ids(d)[0].patient_id_integer == 0] **#HERE IS PROBLEM**

    return results

# some stuff omitted...
# this is the manager of models.DependentPatientId
class DependentPatientIDManager( models.Manager ):
    def get_patient_ids(self, dependent ):
        dpid = self.model.objects.get( dependent = dependent.id )
        return dpid 

1 个答案:

答案 0 :(得分:1)

您需要更改:

from myir import models

from myir.models import DependentPatientID

原因是,您可能已经完成from django.db import models并且名称存在冲突。

现在,

class DependentPatientIDManager( models.Manager ):
    def get_patient_ids(self, dependent ):
        dpid = self.model.objects.get( dependent = dependent.id )
        return dpid 

返回一个对象,而不是一个查询集。所以,DependentPatientID.objects.get_patient_ids(d)[0]会失败。

所以试试这个

if connectedOnly:
    from myir.models import DependentPatientID
    patient_id_integer = 0
    dep_patient_id = DependentPatientID.objects.get_patient_ids(d) 
    if dep_patient_id:
        patient_id_integer = dep_patient_id.patient_id_integer
        results = [d for d in results if patient_id_integer == 0]

        #Or just

        if not patient_id_integer:
            results = []