someone2088 someone2088 - 17 days ago 5
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

project_name
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
Project
objects and assigns them to the list
prjcts
. 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
project_code
whose value was
6SPR
would be assigned to the variable
6Stoke
, 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
6Stoke
part of the line.

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

Edit

Ah, ok- thanks. I changed the variable name, and ran the query again, assigning its results to the variable
sixStokeList
, 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.
    sixStokeList[0]
    &
    sixStokeList[1]
    , I know which one I want, so I've assigned that particular one to a variable with:

    sixStoke = sixStokeList[1]



I have then typed
sixStoke.
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
variable
+
.
+
tab
was different for each
project
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?

Answer

You can't name a variable beginning with a number

Comments