Django .get() raises DoesNotExist error without explicit '__exact' lookup - django

I've faced with issue, which I cannot neither understand nor 'google', while followed steps from "Practical Django Projects" book.
The example of view code below should return specific Entry object (I omitted unnecessary part), but it raises "DoesNotExist: Entry matching query does not exist" error:
...
return render_to_response('weblog/entry_detail.html',
{'entry':Entry.objects.get(pub_date__year=pub_date.year,
pub_date__month=pub_date.month,
pub_date__day=pub_date.day,
slug=slug)
(I confirmed that target object indeed exists, etc.)
When I replaced .get() with filter() method, it returned me queryset with my target object.
After some 'hitting-the-wall' sessions, I managed to make .get() call work when replaced
slug=slug
with
slug__exact=slug
I cannot get the difference between these two. Seems to me, Django's docs clearly state that in such case '__exact' is implied (Django 1.6, "Making queries")
I also cannot check the actual SQL query which Django ran in the .get() cases to compare with SQL query used with .filter() method (the result is either object, not queryset, or raised exception).
So, I actually have 2 workarounds (filter()[0] to get single object, or '__exact'), but I want to understand the weird behavior with .get() method.
My questions are:
Did I misunderstand documentation about '__exact' implication in my case?
If no, isn't my problem a Django/DB bug?
Is there a way to check the actual SQL query which Django has performed, when result of query is not a queryset object?
Thank you!
Note: I run Django 1.6.1 / Python 2.7.3 / MySQL 5.5.33
Update: I installed suggested django-debug-toolbar and was able to compare queries for .get() call with & w/o '__exact' lookup. The only difference that I see between these queries, is the order of 'AND' conditions, so still have no clue what's going on:
slug=slug:
SELECT weblog_entry.id, weblog_entry.title, weblog_entry.excerpt, weblog_entry.body, weblog_entry.pub_date, weblog_entry.excerpt_html, weblog_entry.body_html, weblog_entry.author_id, weblog_entry.slug, weblog_entry.status, weblog_entry.enable_comments, weblog_entry.featured FROM weblog_entry WHERE (EXTRACT(MONTH FROM CONVERT_TZ(weblog_entry.pub_date, 'UTC', 'UTC')) = 2 AND weblog_entry.pub_date BETWEEN '2014-01-01 00:00:00' and '2014-12-31 23:59:59' AND EXTRACT(DAY FROM CONVERT_TZ(weblog_entry.pub_date, 'UTC', 'UTC')) = 2 AND weblog_entry.slug = '3rd-entry' )
slug__exact=slug:
SELECT weblog_entry.id, weblog_entry.title, weblog_entry.excerpt, weblog_entry.body, weblog_entry.pub_date, weblog_entry.excerpt_html, weblog_entry.body_html, weblog_entry.author_id, weblog_entry.slug, weblog_entry.status, weblog_entry.enable_comments, weblog_entry.featured FROM weblog_entry WHERE (EXTRACT(MONTH FROM CONVERT_TZ(weblog_entry.pub_date, 'UTC', 'UTC')) = 2 AND weblog_entry.pub_date BETWEEN '2014-01-01 00:00:00' and '2014-12-31 23:59:59' AND weblog_entry.slug = '3rd-entry' AND EXTRACT(DAY FROM CONVERT_TZ(weblog_entry.pub_date, 'UTC', 'UTC')) = 2)
Note: I've tried to execute these queries manually from mysql console and they both selected target entry;
Update2: I've changed title to point on the problem more precisely.

Ok, let me speak for collective unconscious.
Did I misunderstand documentation about '__exact' implication in my case?
No, you got it right. Let me quote django doc:
As a convenience when no lookup type is provided (like in
Entry.objects.get(id=14)) the lookup type is assumed to be exact.
And since you observe something that contradicts requirements, answer to the next question is:
If no, isn't my problem a Django/DB bug?
Yes, it is a bug. Me and whole Django community will be grateful if you describe steps to reproduce and file an issue
Is there a way to check the actual SQL query which Django has
performed, when result of query is not a queryset object?
Looks you already got the answer :)

Related

Django in_bulk() raising error with distinct()

I have the following QuerySet:
MyModel.objects
.order_by("foreign_key_id")
.distinct("foreign_key_id")
.in_bulk(field_name="foreign_key_id")
foreign_key_id is not unique on MyModel but given the use of distinct should be unique within the QuerySet.
However when this runs the following error is raised:
"ValueError: in_bulk()'s field_name must be a unique field but 'foreign_key_id' isn't."
According to the Django docs on in_bulk here it should be possible to use in_bulk with distinct in this way. The ability was added to Django in response to this issue ticket here.
What do I need to change here to make this work?
I'm using Django3.1 with Postgres11.
As the documentation of in_bulk(…) says:
(…)
Changed in Django 3.2:
Using a distinct field was allowed.
Since you use django-3.1, this will thus not work, you will thus have to upgrade your program to django-3.2.

Primary key validation after Django's sqlsequencereset [duplicate]

I'm following up in regards to a question that I asked earlier in which I sought to seek a conversion from a goofy/poorly written mysql query to postgresql. I believe I succeeded with that. Anyways, I'm using data that was manually moved from a mysql database to a postgres database. I'm using a query that looks like so:
UPDATE krypdos_coderound cru
set is_correct = case
when t.kv_values1 = t.kv_values2 then True
else False
end
from
(select cr.id,
array_agg(
case when kv1.code_round_id = cr.id
then kv1.option_id
else null end
) as kv_values1,
array_agg(
case when kv2.code_round_id = cr_m.id
then kv2.option_id
else null end
) as kv_values2
from krypdos_coderound cr
join krypdos_value kv1 on kv1.code_round_id = cr.id
join krypdos_coderound cr_m
on cr_m.object_id=cr.object_id
and cr_m.content_type_id =cr.content_type_id
join krypdos_value kv2 on kv2.code_round_id = cr_m.id
WHERE
cr.is_master= False
AND cr_m.is_master= True
AND cr.object_id=%s
AND cr.content_type_id=%s
GROUP BY cr.id
) t
where t.id = cru.id
""" % ( self.object_id, self.content_type.id)
)
I have reason to believe that this works well. However, this has lead to a new issue. When trying to submit, I get an error from django that states:
IntegrityError at (some url):
duplicate key value violates unique constraint "krypdos_value_pkey"
I've looked at several of the responses posted on here and I haven't quite found the solution to my problem (although the related questions have made for some interesting reading). I see this in my logs, which is interesting because I never explicitly call insert- django must handle it:
STATEMENT: INSERT INTO "krypdos_value" ("code_round_id", "variable_id", "option_id", "confidence", "freetext")
VALUES (1105935, 11, 55, NULL, E'')
RETURNING "krypdos_value"."id"
However, trying to run that results in the duplicate key error. The actual error is thrown in the code below.
# Delete current coding
CodeRound.objects.filter(
object_id=o.id, content_type=object_type, is_master=True
).delete()
code_round = CodeRound(
object_id=o.id,
content_type=object_type,
coded_by=request.user, comments=request.POST.get('_comments',None),
is_master=True,
)
code_round.save()
for key in request.POST.keys():
if key[0] != '_' or key != 'csrfmiddlewaretoken':
options = request.POST.getlist(key)
for option in options:
Value(
code_round=code_round,
variable_id=key,
option_id=option,
confidence=request.POST.get('_confidence_'+key, None),
).save() #This is where it dies
# Resave to set is_correct
code_round.save()
o.status = '3'
o.save()
I've checked the sequences and such and they seem to be in order. At this point I'm not sure what to do- I assume it's something on django's end but I'm not sure. Any feedback would be much appreciated!
This happend to me - it turns out you need to resync your primary key fields in Postgres. The key is the SQL statement:
SELECT setval('tablename_id_seq', (SELECT MAX(id) FROM tablename)+1);
It appears to be a known difference of behaviour between the MySQL and SQLite (they update the next available primary key even when inserting an object with an explicit id) backends, and other backends like Postgres, Oracle, ... (they do not).
There is a ticket describing the same issue. Even though it was closed as invalid, it provides a hint that there is a Django management command to update the next available key.
To display the SQL updating all next ids for the application MyApp:
python manage.py sqlsequencereset MyApp
In order to have the statement executed, you can provide it as the input for the dbshell management command. For bash, you could type:
python manage.py sqlsequencereset MyApp | python manage.py dbshell
The advantage of the management commands is that abstracts away the underlying DB backend, so it will work even if later migrating to a different backend.
I had an existing table in my "inventory" app and I wanted to add new records in Django admin and I got this error:
Duplicate key value violates unique constraint "inventory_part_pkey"
DETAIL: Key (part_id)=(1) already exists.
As mentioned before, I run the code below to get the SQL command to reset the id-s:
python manage.py sqlsequencereset inventory
Piping the python manage.py sqlsequencereset inventory | python manage.py dbshell to the shell was not working
So I copied the generated raw SQL command
Then opened pgAdmin3 https://www.pgadmin.org for postgreSQL and opened my db
Clicked on the 6. icon (Execute arbitrary SQL queries)
Copied the statement what was generated
In my case the raw SQL command was:
BEGIN;
SELECT setval(pg_get_serial_sequence('"inventory_signup"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "inventory_signup";
SELECT setval(pg_get_serial_sequence('"inventory_supplier"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "inventory_supplier";
COMMIT;
Executed it with F5.
This fixed everything.
In addition to zapphods answer:
In my case the indexing was indeed incorrect, since I had deleted all migrations, and the database probably 10-15 times when developing as I wasn't in the stage of migrating anything.
I was getting an IntegrityError on finished_product_template_finishedproduct_pkey
Reindex the table and restart runserver:
I was using pgadmin3 and for whichever index was incorrect and throwing duplicate key errors I navigated to the constraints and reindexed.
And then reindexed.
The solution is that you need to resync your primary key fields as reported by "Hacking Life" who wrote an example SQL code but, as suggested by "Ad N" is better to run the Django command sqlsequencereset to get the exact SQL code that you can copy and past or run with another command.
As a further improvement to these answers I would suggest to you and other reader to dont' copy and paste the SQL code but, more safely, to execute the SQL query generated by sqlsequencereset from within your python code in this way (using the default database):
from django.core.management.color import no_style
from django.db import connection
from myapps.models import MyModel1, MyModel2
sequence_sql = connection.ops.sequence_reset_sql(no_style(), [MyModel1, MyModel2])
with connection.cursor() as cursor:
for sql in sequence_sql:
cursor.execute(sql)
I tested this code with Python3.6, Django 2.0 and PostgreSQL 10.
If you want to reset the PK on all of your tables, like me, you can use the PostgreSQL recommended way:
SELECT 'SELECT SETVAL(' ||
quote_literal(quote_ident(PGT.schemaname) || '.' || quote_ident(S.relname)) ||
', COALESCE(MAX(' ||quote_ident(C.attname)|| '), 1) ) FROM ' ||
quote_ident(PGT.schemaname)|| '.'||quote_ident(T.relname)|| ';'
FROM pg_class AS S,
pg_depend AS D,
pg_class AS T,
pg_attribute AS C,
pg_tables AS PGT
WHERE S.relkind = 'S'
AND S.oid = D.objid
AND D.refobjid = T.oid
AND D.refobjid = C.attrelid
AND D.refobjsubid = C.attnum
AND T.relname = PGT.tablename
ORDER BY S.relname;
After running this query, you will need to execute the results of the query. I typically copy and paste into Notepad. Then I find and replace "SELECT with SELECT and ;" with ;. I copy and paste into pgAdmin III and run the query. It resets all of the tables in the database. More "professional" instructions are provided at the link above.
If you have manually copied the databases, you may be running into the issue described here.
I encountered this error because I was passing extra arguments to the save method in the wrong way.
For anybody who encounters this, try forcing UPDATE with:
instance_name.save(..., force_update=True)
If you get an error that you cannot pass force_insert and force_update at the same time, you're probably passing some custom arguments the wrong way, like I did.
This question was asked about 9 years ago, and lots of people gave their own ways to solve it.
For me, I put unique=True in my email custom model field, but while creating superuser I didn't ask for the email to be mandatory.
Now after creating a superuser my email field is just saved as blank or Null. Now this is how I created and saved new user
obj = mymodel.objects.create_user(username='abc', password='abc')
obj.email = 'abc#abc.com'
obj.save()
It just threw the error saying duplicate-key-value-violates in the first line because the email was set to empty by default which was the same with the admin user. Django spotted a duplicate !!!
Solution
Option1: Make email mandatory while creating any user (for superuser as well)
Option2: Remove unique=True and run migrations
Option3: If you don't know where are the duplicates, you either drop the column or you can clear the database using python manage.py flush
It is highly recommended to know the reason why the error occurred in your case.
I was getting the same error as the OP.
I had created some Django models, created a Postgres table based on the models, and added some rows to the Postgres table via Django Admin. Then I fiddled with some of the columns in the models (changing around ForeignKeys, etc.) but had forgotten to migrate the changes.
Running the migration commands solved my problem, which makes sense given the SQL answers above.
To see what changes would be applied, without actually applying them:
python manage.py makemigrations --dry-run --verbosity 3
If you're happy with those changes, then run:
python manage.py makemigrations
Then run:
python manage.py migrate
I was getting a similar issue and nothing seemed to be working. If you need the data (ie cant exclude it when doing dump) make sure you have turned off (commented) any post_save receivers. I think the data would be imported but it would create the same model again because of these. Worked for me.
You just have to go to pgAdmin III and there execute your script with the name of the table:
SELECT setval('tablename_id_seq', (SELECT MAX(id) FROM tablename)+1);
Based on Paolo Melchiorre's answer, I wrote a chunk as a function to be called before any .save()
from django.db import connection
def setSqlCursor(db_table):
sql = """SELECT pg_catalog.setval(pg_get_serial_sequence('"""+db_table+"""', 'id'), MAX(id)) FROM """+db_table+""";"""
with connection.cursor() as cursor:
cursor.execute(sql)
This is the right statement. Mostly, It happens when we insert rows with id field.
SELECT setval('tablename_id_seq', (SELECT MAX(id) FROM tablename));

Django - Creating data with or without .create()

I'm following the official Django Tutorial and confused about this part:
Sometimes they create a model data without .create() like:
Poll(pub_date= timezone.now() )
and sometimes they use .create() like:
Poll.objects.create(pub_date= timezone.now() )
From what I run, both returns the same result. So is there any difference?
Thanks
The latter saves it in the table (performs an implicit .save()). The former does not.

email__iexact on django doesn't work on postgresql?

Calling UserModel.objects.filter(email__iexact=email) results in the following query
SELECT * FROM "accounts_person" WHERE "accounts_person"."email" = UPPER('my-email#mail.com')
This doesn't find anything because it there's no EMAIL#MAIL.COM in the database, only email#mail.com. Shouldn't the query have been translated to
WHERE UPPER("accounts_person"."email") = UPPER('my-email#mail.com')?
Summary:
UserModel.objects.filter(email=email) # works
UserModel.objects.filter(email__exact=email) # works
UserModel.objects.filter(email__iexact=email) # doesn't work
Clash you ae right this i also faced the same situtaion with postgres sql .
If you go through This ticket
You will get some idea .
Perhaps an option could be passed to EmailField to state whether you want it to lower all case or not. It would save having to do something in the form validation like.
def clean_email(self):
return self.cleaned_data['email'].lower()
My bad. I had patched lookup_cast to be able to use the unaccent module on postgresql and ended up not calling the original lookup_cast afterwards. The generated query now looks like this WHERE UPPER("accounts_person"."email"::text) = UPPER('my-email#mail.com'). This is the default behavior on django.

IntegrityError duplicate key value violates unique constraint - django/postgres

I'm following up in regards to a question that I asked earlier in which I sought to seek a conversion from a goofy/poorly written mysql query to postgresql. I believe I succeeded with that. Anyways, I'm using data that was manually moved from a mysql database to a postgres database. I'm using a query that looks like so:
UPDATE krypdos_coderound cru
set is_correct = case
when t.kv_values1 = t.kv_values2 then True
else False
end
from
(select cr.id,
array_agg(
case when kv1.code_round_id = cr.id
then kv1.option_id
else null end
) as kv_values1,
array_agg(
case when kv2.code_round_id = cr_m.id
then kv2.option_id
else null end
) as kv_values2
from krypdos_coderound cr
join krypdos_value kv1 on kv1.code_round_id = cr.id
join krypdos_coderound cr_m
on cr_m.object_id=cr.object_id
and cr_m.content_type_id =cr.content_type_id
join krypdos_value kv2 on kv2.code_round_id = cr_m.id
WHERE
cr.is_master= False
AND cr_m.is_master= True
AND cr.object_id=%s
AND cr.content_type_id=%s
GROUP BY cr.id
) t
where t.id = cru.id
""" % ( self.object_id, self.content_type.id)
)
I have reason to believe that this works well. However, this has lead to a new issue. When trying to submit, I get an error from django that states:
IntegrityError at (some url):
duplicate key value violates unique constraint "krypdos_value_pkey"
I've looked at several of the responses posted on here and I haven't quite found the solution to my problem (although the related questions have made for some interesting reading). I see this in my logs, which is interesting because I never explicitly call insert- django must handle it:
STATEMENT: INSERT INTO "krypdos_value" ("code_round_id", "variable_id", "option_id", "confidence", "freetext")
VALUES (1105935, 11, 55, NULL, E'')
RETURNING "krypdos_value"."id"
However, trying to run that results in the duplicate key error. The actual error is thrown in the code below.
# Delete current coding
CodeRound.objects.filter(
object_id=o.id, content_type=object_type, is_master=True
).delete()
code_round = CodeRound(
object_id=o.id,
content_type=object_type,
coded_by=request.user, comments=request.POST.get('_comments',None),
is_master=True,
)
code_round.save()
for key in request.POST.keys():
if key[0] != '_' or key != 'csrfmiddlewaretoken':
options = request.POST.getlist(key)
for option in options:
Value(
code_round=code_round,
variable_id=key,
option_id=option,
confidence=request.POST.get('_confidence_'+key, None),
).save() #This is where it dies
# Resave to set is_correct
code_round.save()
o.status = '3'
o.save()
I've checked the sequences and such and they seem to be in order. At this point I'm not sure what to do- I assume it's something on django's end but I'm not sure. Any feedback would be much appreciated!
This happend to me - it turns out you need to resync your primary key fields in Postgres. The key is the SQL statement:
SELECT setval('tablename_id_seq', (SELECT MAX(id) FROM tablename)+1);
It appears to be a known difference of behaviour between the MySQL and SQLite (they update the next available primary key even when inserting an object with an explicit id) backends, and other backends like Postgres, Oracle, ... (they do not).
There is a ticket describing the same issue. Even though it was closed as invalid, it provides a hint that there is a Django management command to update the next available key.
To display the SQL updating all next ids for the application MyApp:
python manage.py sqlsequencereset MyApp
In order to have the statement executed, you can provide it as the input for the dbshell management command. For bash, you could type:
python manage.py sqlsequencereset MyApp | python manage.py dbshell
The advantage of the management commands is that abstracts away the underlying DB backend, so it will work even if later migrating to a different backend.
I had an existing table in my "inventory" app and I wanted to add new records in Django admin and I got this error:
Duplicate key value violates unique constraint "inventory_part_pkey"
DETAIL: Key (part_id)=(1) already exists.
As mentioned before, I run the code below to get the SQL command to reset the id-s:
python manage.py sqlsequencereset inventory
Piping the python manage.py sqlsequencereset inventory | python manage.py dbshell to the shell was not working
So I copied the generated raw SQL command
Then opened pgAdmin3 https://www.pgadmin.org for postgreSQL and opened my db
Clicked on the 6. icon (Execute arbitrary SQL queries)
Copied the statement what was generated
In my case the raw SQL command was:
BEGIN;
SELECT setval(pg_get_serial_sequence('"inventory_signup"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "inventory_signup";
SELECT setval(pg_get_serial_sequence('"inventory_supplier"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "inventory_supplier";
COMMIT;
Executed it with F5.
This fixed everything.
In addition to zapphods answer:
In my case the indexing was indeed incorrect, since I had deleted all migrations, and the database probably 10-15 times when developing as I wasn't in the stage of migrating anything.
I was getting an IntegrityError on finished_product_template_finishedproduct_pkey
Reindex the table and restart runserver:
I was using pgadmin3 and for whichever index was incorrect and throwing duplicate key errors I navigated to the constraints and reindexed.
And then reindexed.
The solution is that you need to resync your primary key fields as reported by "Hacking Life" who wrote an example SQL code but, as suggested by "Ad N" is better to run the Django command sqlsequencereset to get the exact SQL code that you can copy and past or run with another command.
As a further improvement to these answers I would suggest to you and other reader to dont' copy and paste the SQL code but, more safely, to execute the SQL query generated by sqlsequencereset from within your python code in this way (using the default database):
from django.core.management.color import no_style
from django.db import connection
from myapps.models import MyModel1, MyModel2
sequence_sql = connection.ops.sequence_reset_sql(no_style(), [MyModel1, MyModel2])
with connection.cursor() as cursor:
for sql in sequence_sql:
cursor.execute(sql)
I tested this code with Python3.6, Django 2.0 and PostgreSQL 10.
If you want to reset the PK on all of your tables, like me, you can use the PostgreSQL recommended way:
SELECT 'SELECT SETVAL(' ||
quote_literal(quote_ident(PGT.schemaname) || '.' || quote_ident(S.relname)) ||
', COALESCE(MAX(' ||quote_ident(C.attname)|| '), 1) ) FROM ' ||
quote_ident(PGT.schemaname)|| '.'||quote_ident(T.relname)|| ';'
FROM pg_class AS S,
pg_depend AS D,
pg_class AS T,
pg_attribute AS C,
pg_tables AS PGT
WHERE S.relkind = 'S'
AND S.oid = D.objid
AND D.refobjid = T.oid
AND D.refobjid = C.attrelid
AND D.refobjsubid = C.attnum
AND T.relname = PGT.tablename
ORDER BY S.relname;
After running this query, you will need to execute the results of the query. I typically copy and paste into Notepad. Then I find and replace "SELECT with SELECT and ;" with ;. I copy and paste into pgAdmin III and run the query. It resets all of the tables in the database. More "professional" instructions are provided at the link above.
If you have manually copied the databases, you may be running into the issue described here.
I encountered this error because I was passing extra arguments to the save method in the wrong way.
For anybody who encounters this, try forcing UPDATE with:
instance_name.save(..., force_update=True)
If you get an error that you cannot pass force_insert and force_update at the same time, you're probably passing some custom arguments the wrong way, like I did.
This question was asked about 9 years ago, and lots of people gave their own ways to solve it.
For me, I put unique=True in my email custom model field, but while creating superuser I didn't ask for the email to be mandatory.
Now after creating a superuser my email field is just saved as blank or Null. Now this is how I created and saved new user
obj = mymodel.objects.create_user(username='abc', password='abc')
obj.email = 'abc#abc.com'
obj.save()
It just threw the error saying duplicate-key-value-violates in the first line because the email was set to empty by default which was the same with the admin user. Django spotted a duplicate !!!
Solution
Option1: Make email mandatory while creating any user (for superuser as well)
Option2: Remove unique=True and run migrations
Option3: If you don't know where are the duplicates, you either drop the column or you can clear the database using python manage.py flush
It is highly recommended to know the reason why the error occurred in your case.
I was getting the same error as the OP.
I had created some Django models, created a Postgres table based on the models, and added some rows to the Postgres table via Django Admin. Then I fiddled with some of the columns in the models (changing around ForeignKeys, etc.) but had forgotten to migrate the changes.
Running the migration commands solved my problem, which makes sense given the SQL answers above.
To see what changes would be applied, without actually applying them:
python manage.py makemigrations --dry-run --verbosity 3
If you're happy with those changes, then run:
python manage.py makemigrations
Then run:
python manage.py migrate
I was getting a similar issue and nothing seemed to be working. If you need the data (ie cant exclude it when doing dump) make sure you have turned off (commented) any post_save receivers. I think the data would be imported but it would create the same model again because of these. Worked for me.
You just have to go to pgAdmin III and there execute your script with the name of the table:
SELECT setval('tablename_id_seq', (SELECT MAX(id) FROM tablename)+1);
Based on Paolo Melchiorre's answer, I wrote a chunk as a function to be called before any .save()
from django.db import connection
def setSqlCursor(db_table):
sql = """SELECT pg_catalog.setval(pg_get_serial_sequence('"""+db_table+"""', 'id'), MAX(id)) FROM """+db_table+""";"""
with connection.cursor() as cursor:
cursor.execute(sql)
This is the right statement. Mostly, It happens when we insert rows with id field.
SELECT setval('tablename_id_seq', (SELECT MAX(id) FROM tablename));