someone2088 someone2088 - 2 months ago 9
Python Question

Python- how to query database by class

I have a Python project (I'm quite new to Python), and on one of the webpages, there is a drop-down box which should display a list of all of the projects whose 'status' fields are set to 'live'.

It seems that a couple of particular objects are not being displayed in this drop-down box, so I want to manually query the database to check what their 'status' fields are set to.

How do I manually query the database for these particular projects by their 'project name'/ 'project code', both of which I know are unique?

I've tried getting a list of all of the projects in the shell, so that I can query that list by

for the particular projects that I want using the commands:

from projects.models import Project
prjcts = []
prjcts = Project.objects.all()

This gets all of the
objects and assigns them to the list
. I now want to query that list for a particular project, and have tried doing so like this:

6Stoke = prjcts.get(project_code = 6SPR)

My intention was that the project with the
whose value was
would be assigned to the variable
, so that I could then find look at all of the information for that particular project. However, when I tried running this line in the console, I got a

SyntaxError: invalid syntax

warning which highlighted the end of the
part of the line.

What is wrong with my syntax here? How can I get the project that has the specified
and assign it to a variable?


Ah, ok- thanks. I changed the variable name, and ran the query again, assigning its results to the variable
, i.e.

sixStokeList = Project.objects.filter(project_code = "6SPR")

  • this returned two items, and having printed the elements of the array to the console, i.e.
    , I know which one I want, so I've assigned that particular one to a variable with:

    sixStoke = sixStokeList[1]

I have then typed
and pressed 'tab' in the console to see what's available to this variable. I did the same with another project, i.e.

theFoss = Project.objects.filter(project_code= "1TF")
theFoss. (& pressed 'tab')

The list of available options given after typing
was different for each
instance, even though I had got them both in exactly the same way, which would indicate to me that they are not instances of the same class... how can this be, given that I got them both by querying the same class?


You can't name a variable beginning with a number