This is my query:
SELECT
form_fields.label_name,
entry_details.value,
entry_details.entry_id
FROM
form_fields
JOIN
entry_details ON entry_details.field_id = form_fields.id
WHERE
form_fields.id IN (21401, 21402)
AND entry_details.entry_id = 79;
I am a entry level developer having problem to convert this query into django query... Please help me
Assuming that form_fields model is called FormFields and entry_details is a field on this model then it should be something like:
query = FormFields.objects.filter(
id__in=[21401, 21402], entry_details__id=79)
.select_related(
"entry_details"
).only("label_name", "entry_details__id", "entry_details__value")
I'm not sure about only here. You can try without it first
Related
I'm trying to execute a simple MySQL query that will work on MySQL, while it gives any kind of error on Django.
Here is the query:
Summary = myTable.objects.raw("select FROM_UNIXTIME(unixtime, '%%Y/%%m/%%d') as ndate,count(id) as query_count from myTable group by ndate order by query_count DESC")
This line will give me the following error:
Raw query must include the primary key
But if i edit the query to the following: select id FROM_UNIXITIME....
I will get the following error:
(1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '(unixtime, '%Y/%m/%d') as ndate,count(id) as query_count from myTable' at line 1")
And here is my model:
class myTable(models.Model):
user_id = models.IntegerField()
username = models.CharField(max_length=150)
query = models.CharField(max_length=100)
unixtime = models.IntegerField()
class Meta:
managed = False
db_table = 'mytable'
The query, basically, should only count how many rows there are for this table every day and give the following output: {'2020/06/28': 30, '2020/06/27': 20 ... }. Can anyone help me out on how to make the query work, or at least how to do the same query but using the Django ORM, since using raw queries is being a nightmare? Thanks in advance
This part select id FROM_UNIXITIME.... must have comma after id so it should look like this:
select id, FROM_UNIXITIME....
And also group by must have id so it should look like this (if functions are correct):
select id, FROM_UNIXTIME(unixtime, '%%Y/%%m/%%d') as ndate,count(id) as query_count from myTable group by id,ndate order by query_count DESC
You should prefer to use Django's queryset instead of raw queries .
Basically if you want to count the no of distinct unixtime field in the above table , you can use the below queryset :
myTable.objects.all().values('unixtime').annotate(count = Count('unixtime'))
In the above query , you will get all the unixtime using values queryset and can apply aggregation using annotate to get the distinct unixtime with their coount .
I want to filter my fields in a model dynamically from a form input.
Already searched a lot but did not find something suitable. As i am fairly new to django and all this stuff i might not see some obvious stuff.
The form defines the field to search in and what to search(filter).
This should lead to a url like http://localhost:8000/app/search/?col=id&q=1234
In my view i would like to modify the get_queryset() function with a filter like this:
def get_queryset(self):
query1 = self.request.GET.get('q')
query2 = self.request.GET.get('col')
object_list = mymodel.objects.filter(
Q(query2__icontains = query1)
)
Is this possible?
Moe
Yes, You can do it like this.
>>> query = {f'{query2}__icontains': query1}
>>> object_list = mymodel.objects.filter(**query)
Using Python I try to access a view of a view:
import sqlite3
conn = sqlite3.connect("test.db")
mydb = conn.cursor()
mydb.execute("CREATE TABLE TestTbl (MRTarget_id int, Fullmodel text)")
mydb.execute("CREATE TABLE TestTbl2 (Other_id int, Othermodel text)")
mydb.execute("CREATE VIEW TestView AS SELECT m.ROWID, m.MRTarget_id, m.Fullmodel, t.Othermodel FROM TestTbl m, TestTbl2 t")
mydb.execute("CREATE VIEW TestView2 AS SELECT m.Fullmodel, m.Othermodel FROM TestView m")
mydb.close()
Attempting to create TestView2, I get an error:
sqlite3.OperationalError: no such column: m.Fullmodel
Above SQL statements work fine from SQLite prompt. The database contains views of views; could it be that it is not possible to access these using Python?
I've had the same problem - and I found a solution. I believe your problem is that in your initial view 'TestView', the attribute names are actually m.ROWID, m.Fullmodel etc instead of just ROWID, Fullmodel etc.
A casual look at the views through sqlite manager won't reveal the m. appended to the front of each field name. If you run the Pragma query PRAGMA table_info TestView, the attribute extensions will be revealed.
So, change your TestView creation query to
CREATE VIEW TestView AS
SELECT m.ROWID as ROWID, m.MRTarget_id as MRTarget_id,... etc
and your second Create View query should run successfully - at least it did in my application.
Your code works fine for me.
You could try committing between creating the first view and the second:
conn.commit()
I need to query a SQLAlchemy database by its id something similar to
User.query.filter_by(username='peter')
but for id. How do I do this? [Searching over Google and SO didn't help]
Query has a get function that supports querying by the primary key of the table, which I assume that id is.
For example, to query for an object with ID of 23:
User.query.get(23)
Note: As a few other commenters and answers have mentioned, this is not simply shorthand for "Perform a query filtering on the primary key". Depending on the state of the SQLAlchemy session, running this code may query the database and return a new instance, or it may return an instance of an object queried earlier in your code without actually querying the database. If you have not already done so, consider reading the documentation on the SQLAlchemy Session to understand the ramifications.
You can query a User with id = 1 like this
session.query(User).get(1)
get() is not as your expected sometimes. If your transaction was done:
>>> session.query(User).get(1)
[SQL]: BEGIN (implicit)
[SQL]: SELECT user.id AS user_id, user.name AS user_name, user.fullname AS user_fullname
FROM user
WHERE user.id = ?
[SQL]: (1,)
<User(u'ed', u'Ed Jones')>
If you are in a transaction, get() will give you the result object in memory without query the database:
>>> session.query(User).get(1)
<User(u'ed', u'Ed Jones')>
better to use this:
>>> session.query(User.name).filter(User.id == 1).first()
[SQL]: SELECT user.name AS user_name
FROM user
WHERE user.id = ?
LIMIT ? OFFSET ?
[SQL]: (1, 1, 0)
(u'Edwardo',)
If you use tables reflection you might have problems with the solutions given.
(The previous solutions here didn't work for me).
What I ended up using was:
session.query(object.__class__).get(id)
(object was retrieved by reflection from the database, this is why you need to use .__class__)
I hope this helps.
First, you should set id as the primary key.
Then you could use the query.get() method to query objects by id which is already the primary key.
Since the query.get() method to query objects by the primary key.
Inferred from Flask-SQLAlchemy documentation
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
db = SQLAlchemy()
db.init_app(app)
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
def test():
id = 1
user = User.query.get(id)
Sorry if I'm missing something obvious here as my search isn't turning up anything relevant. I am doing a Django database get query and would like to get each field name during a for loop so that I can do evaluations of it ( if fieldname = "blah") and so on, but I can't seem to figure this out, any advice is appreciated
db_get_data = Modelname.objects.all()
for cur_db_get_data in db_get_data:
#something to get the field name from cur_db_get_data
Try the _meta.fields property.
db_get_data = Model.objects.all()
for cur in db_get_data:
for field in cur._meta.fields: # field is a django field
if field.name == 'id':
print 'found primary key'