简体   繁体   中英

python filter instances of a class

I am new to Python, and am currently trying to debug some Python code.

I have a view which is currently defined like this:

def get_current_budget(project_id, prefetch=False):
""" Find budget by empty version number, or if none, check whether there is one with a current marker """

    if prefetch:
        project = Project.objects.prefetch_related('budget_versions', prefetch).get(id=project_id)
    else: 
        project = Project.objects.prefetch_related('budget_versions').get(id=project_id)

    try:
        #budget = project.budget_versions.get(version_number=None)
        budgets = project.budget_versions.filter(version_number=None)
        print "Latest version of budget: ", project.budget_versions()
        """
        1. Check how many elements have been saved to 'budgets'
        2. Loop through the elements- assign any with no budget items/ presentation date to a test project
        3. Return the element with the budget items/ presentation date
        """
        for budget in budgets:
            if budget.budget_items == "":
                budget.project = "test"
            else:
                budget.project = project

        return budget
    except ObjectDoesNotExist:
        try:
            budget = project.budget_versions.filter(version_number=0).order_by('-presentation_date')[0]
            print "Latest verions of budget (execpt- try): ", project.budget_versions()
            return budget
        except IndexError:
            print 'Budgets found', project.budget_versions.all()
            return None 

The purpose of this view is to take a parameter of a 'project id', and, based on that ID, return the latest version of the budget belonging to that project, assigning all of the 'older' budgets to a list.

However, when I try to run this view in a Python shell, using the command get_current_budget(5915) (I know that '5915' is the ID of one of the projects in the database), I get a KeyError , which says:

KeyError Traceback (most recent call last) in () ----> 1 get_current_budget(5915)

It also gives the message:

We use **kwargs rather than a kwarg argument to enforce the

 504 # `manager='manager_name'` syntax. 

I don't really understand what this means... can someone explain it to me? What am I doing wrong here?

Try being specific with

get_current_budget(project_id=5915)

to see what happens.

Also, the second message you see is apparently a comment, likely from GenericRelationObjectManager found here . I'm not certain why you are seeing it, though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM