﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
13941	importing fixtures to postgres fails to set sequences correctly	Ales Zoulek	jbronn	"there seems to be a problem with django postgres backend, when
importing data from fixtures. Data are imported correctly, but the
sequences for primary keys are set incorrecly on models that have
generic.GenericRelation field. See example:

As a demo, those are just two models with generic relation.

{{{
#!python
models.py:
----------
from django.db import models
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType


class Tag(models.Model):
   name = models.CharField(max_length=30)
   content_type = models.ForeignKey(ContentType)
   object_id = models.PositiveIntegerField()
   content_object = generic.GenericForeignKey('content_type', 'object_id')


class Post(models.Model):
   name = models.CharField(max_length=30)
   text = models.TextField()
   tags = generic.GenericRelation('blog.Tag')
}}}

The loaddata management command calls at the end

connections[DEFAULT_DB_ALIAS].ops.sequence_reset_sql command

 to update sq1 sequences. Let's see the result:

{{{
#!python
./manage shell
-------------------
In [1]: from django.db import DEFAULT_DB_ALIAS, connections
In [2]: from django.core.management.color import no_style
In [3]: from proj.blog.models import Post
In [4]: connections[DEFAULT_DB_ALIAS].ops.sequence_reset_sql(no_style(), [Post])
Out[4]:
['SELECT setval(pg_get_serial_sequence(\'blog_post\',\'id\'),
coalesce(max(""id""), 1), max(""id"") IS NOT null) FROM ""blog_post"";',
 'SELECT setval(pg_get_serial_sequence(\'blog_post\',\'id\'),
coalesce(max(""id""), 1), max(""id"") IS NOT null) FROM ""blog_tag"";']
}}}

As you can see, the problem is in the last ""SELECT"". Postgres backend
""thinks"" that Post.tags is m2m relation with usual m2m sql table and
tries to update it's pk sequence. The table is of course non existant
and it resets Post.pk sequence to max(Tag.pk), this is obviously
incorrect behaviour and results with potential DatabaseErrors
duplicate key on blog_post table.
Removing Post.tags and accessing related tags directly works as a
workaround, but not very nice and comfotable one.."		closed	Database layer (models, ORM)	dev		fixed	postgres fixture		Unreviewed	1	0	0	0	0	0
