I'm trying to work with Databases using Django's ORM.
I'm looking to retrieve a value from a specific column in a database and then convert it from a QuerySet type to a Int or String so I can then work with this data.
So my question is, how can I convert a QuerySet to a usable data type?
EDIT:
I'm currently building a calorie tracker.
I want to grab the column values for "protein", "fat" and "carbs" from my MacroGoal database. There is only one row in the database and therefore only one value in each column.
I know I can do this using data = MacroGoal.objects.all()
and it gives me :
<QuerySet [<MacroGoal: ctracker Fat: 45 Protein: 45 Carbs: 45>]>
I now want to be able to use those values from each column(or key in this instance). I need to convert each column value to an integer.
How can be this done?
-
Gosh there are many ways to answer this! Please start with the official docs of making queries here. You could use values(), you could extract in a loop, or step over an interator, even cast to a list and pull the index (if you know it)LouieC– LouieC2020年12月03日 12:27:19 +00:00Commented Dec 3, 2020 at 12:27
-
I'm trying to retrieve data that is being constantly updated. I can't use filter(columnname='value') as I don't know what that value isContinuit– Continuit2020年12月03日 12:29:43 +00:00Commented Dec 3, 2020 at 12:29
-
Could you post some code for us to work with? And an example use case as well. A query using filter() would usually have some conditions, using values() would only extract the columns that you specify. Does the database have one row, or multiple? We need more information pleaseLouieC– LouieC2020年12月03日 12:41:03 +00:00Commented Dec 3, 2020 at 12:41
-
Hi Louie, just updated it, any help would be great, thank youContinuit– Continuit2020年12月03日 14:10:21 +00:00Commented Dec 3, 2020 at 14:10
-
1Answer from iri should give you want you need. If it does, please accept it as the answer to close the question. If it doesn’t, kindly write back and the community will continue to helpLouieC– LouieC2020年12月03日 21:08:04 +00:00Commented Dec 3, 2020 at 21:08
1 Answer 1
Please refer to the django ORM docs, they are very thorough: https://docs.djangoproject.com/en/3.1/topics/db/queries/
If there is only ever going to be one row in the database you can do:
obj = MacroGoal.objects.first()
This gets the first row out of the database, and then to get specific information from the object you would do something like
obj.<field_name> and that would give you the value stored in the database, so if you have a field called protein in your model you would do obj.protein to get the value stored in the protein column.