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?
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.
Related
I have a collection in MongoDB, I need to find a collection where: "user_id" : 965554753650192394, and in this collection there is a column with `"coins"' and I need to display the data of this column
I tried to implement it via
user = collection.find_one({})
print(user)
But this method is not suitable because initially you need to know the contents of the column.
That is, I need to find the "user_id", and then find the "coins" column data in this collection and display them in the column and display data from this column(python)
I have two object called RECEIPT and PARTICULAR.
Attributes of RECEIPT object are:
receiptNo
particularList
Attributes of PARTICULAR object are:
particularId
particularName
Also I have their respective tables. receiptNo is the primary key of RECEIPT table and it is the foreign key in PARTICULAR table. So for a receipt there are multiple particulars.
I want to fetch data to populate RECEIPT object. To achieve this I can first run select query to RECEIPT table and by iterating the result using a for loop I can run another query to fetch the PARTICULAR table. Here I am calling the DB twice.
To avoid calling DB twice I tried joins also as:
SELECT * FROM RECEIPT r,PARTICULAR p WHERE r.RECEIPT_NO = p.RECEIPT_NO
However as it returns repetitive data for the RECEIPT, i.e. for each PARTICULAR row corresponding RECEIPT data are also fectching. This RECEIPT data are repetitive as multiple particularId shares same receiptNo. Due to thisI am unable to load the data properly to the RECEIPT object (Or may be I dont know how to load such resulset to the respective objects)
My actual requirement is to load RECEIPT object by forming PARTICULAR list for each receipt.
Is using the for loop and calling DB twice the only way to achieve it?
Suggest me an efficient way to achieve this
I think querying the data from the database with the JOIN approach is the most efficient way to do it.
If you make sure to ORDER BY "RECEIPT_NO" you just have to loop through the list once in python, only creating a new Receipt object every time you reach a new "RECEIPT_NO".
So the SQL becomes:
SELECT * FROM RECEIPT r,PARTICULAR p WHERE r.RECEIPT_NO = p.RECEIPT_NO ORDER BY RECEIPT_NO
And the python code could look like
data = query("SELECT * FROM RECEIPT r,PARTICULAR p WHERE r.RECEIPT_NO = p.RECEIPT_NO ORDER BY RECEIPT_NO")
last_receipt_nr = ""
for row in data:
if last_receipt_nr == row.RECEIPT_NO:
# Replace with code initializing a new Receipt object
last_receipt_nr = row.RECEIPT_NO
#Replace with code initializing a new Particular object
I have search option which user input from front end.
search = {"Date":"2016-02-07","Status":"pass" }
Then I am mapping with those values with column names in DB.
query_to_field_mapping = {"Date": "date","Status": "result"}
query = {query_to_field_mapping[key]: value for key, value in search.items()}
Now I have DateTimeField in DB. When I am using filter I am trying with below one:
result = Customer.objects.filter(**query)
Here am trying to filter as per date field & want to get the filtered record as well. I tried the same with no success .How can I proceed?
Any help ll be awesome!!!
I tried the some other question from SO: How can I filter a date of a DateTimeField in Django?
I couldn't get a way to solve my problem as there we are passing a column name 1 by 1 .But right now I am passing as dictionary.
Your approach is the correct one. The reason why it doesn't work is because you filter for equality of datetime field by providing a date string, therefore a 2016-02-07 date (your query param) does not equal 2016-02-07T12:32:22 (a possible value in the DB).
To overcome this situation, use one of the field lookups possibilities from the link of your own question. As a specific example, let's use a contains field lookup, like so:
query_to_field_mapping = {"Date": "date__contains","Status": "result"}
Thus, when passing the query_to_field_mapping to .filter(), it will look for the date within the datetime that you need.
So I am using django with mysql, and I have a model MyModel, which contains some items with None on the region field. When I run this:
results = MyModel.objects.all()\
.values('region')\
.annotate(total=Count('region'))
it returns the grouping correctly, but one is {'None': 0}, which is incorrect, because there are some items with region field equal to None.
Now, if I were using mysql then I could group this with:
select region, count(id) from model_table group by region;
which returns the solution I want | NULL | 5 |.
How can I achieve this from django?
You actually already wrote the answer in your question. As far as I know, COUNT in SQL excludes certain falsey values like NULL. So if you want to count the falsey values as well, you use another field to perform the aggregate, just like you did in your SQL statement where you used the 'id' field. On that note, all you need to do is to perform COUNT on 'id'. Change your code to something like this:
results = MyModel.objects.all()\
.values('region')\
.annotate(total=Count('id'))
I created a new property for my db model in the Google App Engine Datastore.
Old:
class Logo(db.Model):
name = db.StringProperty()
image = db.BlobProperty()
New:
class Logo(db.Model):
name = db.StringProperty()
image = db.BlobProperty()
is_approved = db.BooleanProperty(default=False)
How to query for the Logo records, which to not have the 'is_approved' value set?
I tried
logos.filter("is_approved = ", None)
but it didn't work.
In the Data Viewer the new field values are displayed as .
According to the App Engine documentation on Queries and Indexes, there is a distinction between entities that have no value for a property, and those that have a null value for it; and "Entities Without a Filtered Property Are Never Returned by a Query." So it is not possible to write a query for these old records.
A useful article is Updating Your Model's Schema, which says that the only currently-supported way to find entities missing some property is to examine all of them. The article has example code showing how to cycle through a large set of entities and update them.
A practice which helps us is to assign a "version" field on every Kind. This version is set on every record initially to 1. If a need like this comes up (to populate a new or existing field in a large dataset), the version field allows iteration through all the records containing "version = 1". By iterating through, setting either a "null" or another initial value to the new field, bump the version to 2, store the record, allows populating the new or existing field with a default value.
The benefit to the "version" field is that the selection process can continue to select against that lower version number (initially set to 1) over as many sessions or as much time is needed until ALL records are updated with the new field default value.
Maybe this has changed, but I am able to filter records based on null fields.
When I try the GQL query SELECT * FROM Contact WHERE demo=NULL, it returns only records for which the demo field is missing.
According to the doc http://code.google.com/appengine/docs/python/datastore/gqlreference.html:
The right-hand side of a comparison can be one of the following (as
appropriate for the property's data type): [...] a Boolean literal, as TRUE or
FALSE; the NULL literal, which represents the null value (None in
Python).
I'm not sure that "null" is the same as "missing" though : in my case, these fields already existed in my model but were not populated on creation. Maybe Federico you could let us know if the NULL query works in your specific case?