Reputation: 36
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?
Upvotes: 0
Views: 72
Reputation: 744
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.
Upvotes: 1