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 .
Related
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
My constrains method not working for id_number. can't figure it out why.
from odoo import models, fields, api
from odoo.exceptions import ValidationError
class KindeGarden(models.Model):
_inherits = {'res.partner': 'partner_id'}
_name = 'kindergarten.model'
_description = 'Kindergarten'
age = fields.Integer(string="Amžius", required=False, default="1")
group = fields.Char(string="Grupė", compute="_compute_group", store=True)
height = fields.Float(string="Ūgis", required=False)
weight = fields.Float(string="Svoris", required=False)
id_number = fields.Integer(string="Registravimo Nr", required=True)
#api.constrains('id_number')
def _check_id_number_field(self):
for i in self:
if i.id_number < 10:
raise ValidationError("Number is to small")
and i'm also having this
WARNING -Kindegarden odoo.models.schema: Table 'kindergarten_model': unable to set a NOT NULL constraint on column 'id_number' !
If you want to have it, you should update the records and execute manually:
ALTER TABLE kindergarten_model ALTER COLUMN id_number SET NOT NULL
Like mentioned above, it looks like it is some data are null already before you set required parameter to true.
odoo has a shell you can use to access your DB if you are not familiar with SQL.
odoo-bin -d <database_name> shell
inside the shell, do as follow so you will see.
>> records = env['kindergarten.model'].search([('id_number','=',False)])
>> len(records)
if it returns a number aside from 0, it means that those are NULL value. so do like.
>> for record in records:
record.write({'id_number': 0.0})
>>env.cr.commit()
Then update your module again.
If this doesn't work you will need to do it manually with SQL.
Did you add constraint after few records were added ?
The error you got generally comes when postgres is unable to set "NOT NULL" to the column because it already has null values
Postgres model:
class Song(db.Model):
id3_parsed = db.Column(db.Boolean, server_default=u'false')
Running the following query gives the correct count:
select count(*) from song where id3_parsed is false;
But how do I do it with flask-sqlalchemy? This doesn't work:
songs = Song.query.filter(Song.id3_parsed == False).all()
songs = Song.query.filter(Song.id3_parsed.is_(False)).all()
Your query seems to be right, looks like this is flake8 issue.
And that you can ignore by adding # noqa in the line you wrote.
I want to do a Django Python MySQL query with WHERE (in sql) being a link generated from a previous query.
Hereby I paste my actual code:
def population(request):
db = MySQLdb.connect(user='xxxx', db='xxxxdb', passwd='xxxxpwd', host='localhost')
cursor = db.cursor()
cursor.execute("SELECT last_name FROM a_population WHERE country='Denmark' ORDER BY last_name")
denominazione_comune = cursor.fetchall();
rows_count = cursor.rowcount
db.close()
counter = 0
return render_to_response('list_last_name.html', {'lastname': last_name}, context_instance=RequestContext(request))
So from this code I get an (un)ordered list of family names. By clicking one of these family names I would like to create another query with the family name clicked as a parameter but I don't have a clue of how to do that.
Thanks a million to whom will give me some input.
I am using sql alchemy in my project.
I have one problem when two or more tables are joined or have foreign key relation then i am unable to query on joined tables attribute in where condition.
Eg. I have notice table and a user table user.id is foreign key of notice.sender
now I want to search notice by user.name
notice table:[id, sender(FK user.id), receiver(FK user.id), subject, message, status]
user table: [id, name, email, address, status]
Join in notice model:
sender_user = relationship('User', primaryjoin='Notice.sender==user.id', backref=backref("sender_user"))
receiver_user = relationship('User', primaryjoin='Notice.receiver==user.id', backref=backref("receiver_user"))
SQL alchemy filter query:
user_name='john'
notice=db_session.query(Notice)
notice = notice.filter(Notice.sender_user.name == user_name)
Following query doesn't works:
notice=db_session.query(Notice)
notice = notice.filter(Notice.user.name == user_name)
Please help!
You need to acquire a session object, then do:
query = session.query(Notice).filter(Notice.sender_user.name == user_name)
results = query.all()
If that does not work (you don't get the results you expect), try doing this:
session.query(Notice, User.name).filter((Notice.sender_user.id == User.id) & (User.name == user_name))
results = query.all()
I suppose you also have a field called sender which is the id of the user. Then, this should also work:
session.query(Notice, User.name).filter((Notice.sender == User.id) & (User.name == user_name))
Retry all of them, I made some small modifications. (you can see them in revision history). It would be weird if they don't work... (If they don't, try posting the question on the SQLAlchemy mailing list)