Limiting the number of records return with getattr in django model

currently working on a billing application for multi company database. Where some data are company code dependent and some are not. to filter the data for each data model i am trying to make a generic function to filter each data model.

i am using a Model level indication for each data model to know if the data is company dependent or not. my generic method is like below.

def filter_Company_or_Group(dbModelName, compGroup, compId, filter = {}, ModelLevel = '', 
      orderByField = '', recordLimit = -1, unique = False):
if ModelLevel == '':
    ModelLevel = getdbModelLevel(dbModelName)

if ModelLevel == '':
    ModelLevel = 'Global'

q_objects = Q()
modelFilter = {}
if ModelLevel == 'Company':
    modelFilter = {'company_id' : compId}
    q_objects = Q(company_id = compId)
if ModelLevel == 'Group':
    modelFilter = {'company_Group_id' : compGroup}
    q_objects = Q(company_Group_id = compGroup)

if ModelLevel == 'Company OR Group':
    q_objects |= Q(company_id = compId)
    q_objects |= Q(company_Group_id = compGroup)

if ModelLevel == 'Global' or ModelLevel == 'ANY':
    q_objects = Q()

if filter != {}:
    for key, value in filter.items():
        q_objects &= Q(**{key: value})

if orderByField == '' :
    orderByField = 'id'
    
objList = getattr(billing.models, dbModelName).objects.order_by(orderByField).filter(q_objects)

    
if recordLimit != -1:
    objList = objList[:recordLimit]

return objList

here method getdbModelLevel return the level of the method if its company dependent or not.

my question is when i try to limit the number of rows to 1, it is not working as method first() but for each return, need to make an if statement, e.g.

filters = {'UOM_Code' : 'MT' }
objUOM = filter_Company_or_Group('UOM',compGroup, compId, filters,'','',1)

objUOM = UOM.objects.filter(company_id = compId, UOM_Code = 'MT').first()

if objUOM:
    objUOM = objUOM[0]

also how should i get the unique records?

Thanks

Back to Top