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
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 have this small project to create my bills through Django and Latex which worked flawlessly until today. Now when I try to add another costumer, Django throws
duplicate key value violates unique constraint "kunden_kundearbeitsamt_pkey"
DETAIL: Key (id)=(4) already exists.
These are the model definitions in question:
class Kunde(models.Model):
name = models.CharField('Name', max_length = 200)
vorname = models.CharField('Vorname', max_length = 200)
geburtsdatum = models.DateField('Geburtsdatum', max_length = 200)
untersuchungsdatum = models.DateField('Untersuchungsdatum', max_length = 200)
class Meta:
abstract = True
class KundeArbeitsamt(Kunde):
kundennummer = models.CharField('Kundennummer', max_length = 100)
bglnummer = models.CharField('BGL-Nummer', max_length = 100)
empfaenger = models.ForeignKey('rechnungen.NumberToEmpfaenger', blank = True, null = True)
class Meta:
verbose_name = "Proband Arbeitsamt"
verbose_name_plural = "Proband Arbeitsamt"
def __str__(self):
return '{}, {}'.format(self.name, self.vorname)
The admin part where the object is created (nothing special, I guess):
from django.contrib import admin
from .models import KundeArbeitsamt
class KundeArbeitsamtAdmin(admin.ModelAdmin):
ordering = ('name',)
admin.site.register(KundeArbeitsamt, KundeArbeitsamtAdmin)
I swear, I did not make any migrations or other changes to the database (Postgres) whatsoever. Django is handling the creation of the objects. What is causing this error and how to fix it?
This error is raised by your database, because django wants to add an new column with an ID (=4) already in use.
To investigate further you need to find the part of your app responsible for creating the IDs. Django usually delegates this task to your database. In case of postgres the datatype serial is used. Postgres uses so called sequences for this purpose and generates and executes the following SQL for you:
CREATE SEQUENCE tablename_colname_seq;
CREATE TABLE tablename (
colname integer NOT NULL DEFAULT nextval('tablename_colname_seq')
);
ALTER SEQUENCE tablename_colname_seq OWNED BY tablename.colname;
I would now start with checking the database sanity like that:
-- views contents of the table
SELECT * FROM kunden_kundearbeitsamt;
-- check the sequence
select currval('kunden_kundearbeitsamt_id_seq');
If the first shows 4 records with IDs 1, 2, 3 and 4 and the sequence answers with 4 everything is alright. I would proceed with the django sources to figure out why they pass an ID on object creating without relying on the sequence. The django shell might be a good place to start with in that case.
Otherwise I would fix the sequence and ask myself how this happend as it is barely the case that postgres makes mistakes at this point.
SELECT setval('kunden_kundearbeitsamt_id_seq', (SELECT max(id) FROM kunden_kundearbeitsamt));
I want to create a table in SQLite with Python where the column names will be stored in a variable.
import sqlite3 as lite<br>
con = lite.connect('MyData.db')
name = raw_input() # I am taking values from user here
id1 = raw_input()
a=con.execute("CREATE TABLE PROD_SA_U_1(
name TEXT,
ids INT")
Instead of the column being named as "name","id" , I want what the user inputs.
You could simply substitute the names the user provides in the query string.
Example:
import sqlite3 as lite
con = lite.connect('MyData.db')
field_1 = raw_input()
field_2 = raw_input()
query = "CREATE TABLE PROD_SA_U_1( %s TEXT, %s INT)"
a = con.execute(query % (field_1, field_2))
However, note that this approach is vulnurable to running incorrect queries if the fields are not validated, so you should sanitise the fields before passing them further. For example, a malicious user might pass a Drop database query within your arguments.
I am building a service that makes short URLs. I have the models:
from django.db import models
class ShortURL(models.Model):
url = models.CharField(max_length = 50)
class LongURL(models.Model):
name = models.CharField(max_length = 100, null=True)
url_to_short = models.ForeignKey(ShortURL)
I have already run the command: python manage.py migrate
If I open the interpreter, using python manage.py shell and run this code:
>>> from appshort.models import LongURL
>>> a = LongURL(name = 'hello_long_link')
>>> a.save()
then I get the error:
django.db.utils.IntegrityError: NOT NULL constraint failed: appshort_longurl.url_to_short_id
What did I do wrong?
class LongURL(models.Model):
name = models.CharField(max_length = 100, null=True)
url_to_short = models.ForeignKey(ShortURL)
The way you have set it up, the url_to_short foreign key is not optional. So when you try to save:
>>> a = LongURL(name = 'hello_long_link')
>>> a.save()
Django is trying to tell you that you didn't provide the url_to_short relation on your a model instance.
You'll need to either
Provide the ShortURL relation when you create the LongURL instance
Make the url_to_short relation optional with null=True, blank=True.
While creating an entry for LongURL you must create an object of ShortURL or filter out already existing (because ForeignKey field cannot be left blank). Additionally, you say that sometimes you have been able to achieve the desired behaviour. This can be so because at those places you would have got an object of ShortURL which is not null. However, the error in the discussion arises, when you try to send a null object during the creation of LongURL. For example:
...
short_url_obj = ShortURL.objects.filter(...).first()
# you have to ensure that this above query is not null
try:
new_long_url = LongURL(url_to_short=short_url_obj, name="some_name")
new_long_url.save()
except:
# if the short_url_obj is null
print("The short_url_obj was null, cannot save to database")
...
One can also use if-else block instead, but I would not advice that.
if is_admin == True:
admin_users = Group(name = 'Admin')
try:
admin_users.save()
except:
log.info("Admin Group already exists")
pass
group_id = Group.objects.get(name='Admin').id
If in the data that I get 'is_admin' is true then I will create the group 'Admin' if not existed then save it and fetches the id of that group-'Admin'. This id will be saved in the userinfo with Group as a foreign key.
The following query should give me the id of that group.
group_id = Group.objects.get(name='admin').id
Instead it is saying
current transaction is aborted, commands ignored until end of transaction block
I am using the postgresql database I don't know why it is giving me the error while executing this query. Please tell me how to write the query.
What are you trying to achieve is already in django: get_or_create. Using this your code should look like
group, created = Group.objects.get_or_create(name='Admin')
if created:
log.info("Admin Group already exists")
group_id = group.pk
pk is a convenience property on all django models that always point to a primary key field, no matter if it's autocreated or specified explicitly.