I have a Model with a JSONField:
class MyModel(models.Model):
locale_names = models.JSONField()
The shape of the JSON Field is simple: keys are language codes (en, fr...) and values are translated strings.
I'm trying to build a search query that does an unaccented icontains search on a translated value:
MyModel.objects.filter(locale_names__en__unaccent__icontains="Test")
This does not give the expected results, because Django interprets "unaccent" as a key to look up in the JSON, rather than the unaccent PostgreSQL function:
-- Expected SQL query: something like
SELECT "app_model"."*" ...
FROM "app_model"
WHERE UPPER(UNACCENT("app_model"."locale_names" ->>'en')::text)) LIKE UPPER(UNACCENT('%Test%'))
LIMIT 21
-- Actual SQL query
SELECT "app_model"."*" ...
FROM "app_model"
WHERE UPPER(("app_model"."locale_names" #>> ARRAY['en','unaccent'])::text) LIKE UPPER('%Test%')
LIMIT 21
How can I tel Django to interpret __unaccent as the PostgreSQL function rather than a JSON path?
EDIT:
I'm using Django 3.2
Doing __unaccent__icontains lookups on regular CharFields works as expected.
Unfortunately, JSONField does not support unaccent lookup.
cf. documentation :
The unaccent lookup can be used on CharField and TextField:
As a complement to #Benbb96's answer above, my workaround was to write the WHERE clause I needed using the soon-to-be-deprecated QuerySet.extra method:
MyModel.objects.extra(
where=[
"UPPER(UNACCENT((app_model.locale_names->>'en')::text)) LIKE UPPER(UNACCENT(%s))"
],
params=("Test",)
)
As requested by the Django team, I created a ticket with them so that this use case can be addressed without QuerySet.extra().
Im trying to import existing oracle tables in django.
Installed cx_oracle and i did all the steps for django to communicate with my oracle db.
import cx_Oracle
con = cx_Oracle.connect("PYTHON","PYTHON", "METDBR")
cur = con.cursor()
cur.execute("select * from ICUSTOMER")
res = cur.fetchall()
for row in res:
print(row)
works fine....
when im trying to inspect the table with the command
python manage.py inspectdb icustomer
i get
Unable to inspect table 'icustomer'
The error was: ORA-00942: table or view does not exist
Usually, it is about letter case.
By default, Oracle stores table names in UPPERCASE. If you (or whoever created the table) used mixed case and enclosed table name into double quotes, you have to reference the table exactly like that: using the same letter case (as created), enclosed into double quotes.
Therefore, check exact table name.
Check the USER that is configured in your default ENGINE, this is very probably not the user PYTHON.
You must than qualify the inspected table as PYTHON.ICUSTOMER
and grant the access on it the the engine user (while connected as PYTHON)
GRANT SELECT on PYTHON.ICUSTOMER to <engine user>;
Im trying to use the datatables jQuery plugin with date/datetime fields. and when you make the query that contains those field generates a MySQL Warning when you try to use __contains in the queryset. I've detected that if you try to make queries over Year, Month and Day the warning doesn't appears.
There's another way to search in a date/datetime field without raise that warning or how could I make a query over a year/month/day in a date/datetime field.
Here is an example:
Model.objects.filter(Date__contains="2014")
Which gives this warning:
Warning: Incorrect date value: '%2014%' for column 'Fecha' at row 1
I'd like to make a query like this:
SELECT * FROM Model WHERE YEAR(Date) LIKE "%4%" OR MONTH(Date) LIKE "%4%" OR DAY(Date) LIKE "%4%";
The best solution that I´ve found is searching by a Regex
Model.objects.filter(Date__regex="4")
Model.objects.filter(field_name__year=2014)
I like to convert tables (100+) living in access database to a geodatabase tables, sorting them and deleting unnecessary fields in each table at the same time. I figured I use the Sort_management method to convert and sort the tables followed by DeleteFieldd_management method to delete the fields. Here is the code that I have written,
import arcpy
from arcpy import env
env.workspace = "E:\Database Project\ACS Estimate 2011\ACS 2011 Tables.mdb"
tableList = arcpy.ListTables()
for table in tableList:
out_dataset = "E:\Database Project\ACS Estimate 2011\Data\To Database\Seq Tables.gdb"
#Process: Sort
arcpy.Sort_management(table, out_dataset, "GEOID ASCENDING", "UR")
#Process: Delete Field
arcpy.DeleteField_management(out_dataset, "FILEID;FILETYPE;STUSAB;CHARITER")
I am getting the following error message,
Any help is greatly appreciated. Thank you in advance.
Try setting out_dataset before entering the loop (immediately after tableList = arcpy.ListTables() and see if it gets past the "already exists" error.
to follow on #Evan, you could erase the table if it pre-exists.
if arcpy.Exists(out_dataset):
arcpy.Delete_management(out_dataset)
Also, if I know I'm going to be recreating a table over and over and I don't want to write checks like this into my code, I use:
arcpy.env.overwriteOutput=True
If this table type isn't really recognized by arcpy, then you could do an analogous "if-exists" thing w/just python's os module or something else along those lines.
I have a Django project powered by a MySQL database. I fed the database a CSV file (via raw SQL statements) with some 600 records. That went smoothly (almost, there was one error of Field 'customer_id' doesn't have a default value - no idea why). The problem is that these records are not showing up in the webapp itself.
For example, the CSV file contained a list of about 600 records describing client contact info. When I fire up the Django test server and go to the client contact page (which should list all the contact records -- the 600) nothing is there. Further, when I go into the Admin section and view the client contact records, there is nothing there -- However it shows that there is a total of 600 records right beside the pagination buttons. Also, there are 7 pages (7 pagination buttons) of records -- of course, there is nothing on any page.
What the heck?!
EDIT for More Details
The file I am trying to import is called subset_ressy_esc.csv and a couple of lines of it look like this:
R0138,Y,1432 MyRoad Ct,MyCity, MyProv,H0H 0H0,N,100.00,0,1,1
R0140,Y,268 MyStreet Link,MyCity,MyProv,H0H 0H0,N,100.00,0,1,1
R0142,Y,10994 123 St,MyCity,MyProv,H0H 0H0,N,0.00,1,0,0
And the fields they represent (in the same order shown above) are:
systemID (pk), isRessy, systemAddress, systemCity, systemProvince, systemPostalCode, isHoseBibb, servicePreauthAmt, noWorkRequired, SUAuthorized, BDAuthorized
Now the isRessy and isHoseBibb fields are select style fields, where the user selects from a drop down, while the noWorkReqd, SUAth, and BDAuth are booleans. The serviceAmt is a decimal (dollar) amt.
To import this data, I go into the mySql interpreter mysql -u garfonzo -p and run the following command:
mysql> load data local infile '/home/garfonzo/subset_ressy_esc.csv' into table systems_system fields terminated by ',' lines terminated by '\n' (systemID, isRessy, systemAddress, systemCity, systemProvince, systemPostalCode, isHoseBibb, servicePreauthAmt, noWorkRequired, SUAuthorized, BDAuthorized);
Query OK, 684 rows affected, 1 warning (0.01 sec)
Records: 684 Deleted: 0 Skipped: 0 Warnings: 0
mysql> show warnings;
+---------+------+-----------------------------------------------------+
| Level | Code | Message |
+---------+------+-----------------------------------------------------+
| Warning | 1364 | Field 'systemOwner_id' doesn't have a default value |
+---------+------+-----------------------------------------------------+
When I do a SELECT * FROM systems_system I spits out all 684 records, with all the right data. When I open the django project, nothing is listed but the admin has 7 pages of systems, without a single system actually present -- just 7 pages of nothing.
Any ideas?
Interesting. The fact that the admin shows the correct record count means that the table names match (that was my first thought). So it sees the app, the table, and the record count. My guess is one of two things:
You did not define a __str__() or __unicode__() method for the class, or
You did not set up the matching admin.py classes correctly and you are display a blank field.
My money is on number one.
Are you sure that you have actually saved those records via .save() method?
What does console show? I mean have you tried to manually iterate in shell? (manage.py shell)
And lastly have you tried to restart the server?
Admin should not require __str__ nor __unicode__.
Looking at the warning of Field systemOwner_id doesn't have a default value didn't really bother me. But it suddenly dawned on my that I am not importing a value for that field, and that field cannot be empty. So, (for testing purposes) I changed my model so that that field systemOwner_id can be null, ran the same MySQL import and, voila, all systems are present. Nice!!
Thanks for the help -- working through this on this Q&A has helped solve my problem.
Cheers!