Custom primary key and ModelSerializer

820 views
Skip to first unread message

Jean-Philippe B

unread,
Jan 4, 2013, 2:20:14 PM1/4/13
to django-res...@googlegroups.com
Hi all,

I'm still learning how to use this nice framework and I noticed something weird with models that have a custom primary_key, but maybe I miss something.

Here are some simple models and their serializers:

 class ObjectA(models.Model):
     uuid = models.CharField(max_length=50)
 
 class ObjectASerializer(serializers.ModelSerializer):
     class Meta:
         model = ObjectA

 class ObjectB(models.Model):
     uuid = models.CharField(max_length=50, primary_key=True)

 class ObjectBSerializer(serializers.ModelSerializer):
     class Meta:
         model = ObjectB

With ObjectASerializer I can create objects from a serialized form:

>>> s = ObjectASerializer(data={"uuid": "foo"})
>>> s.is_valid()
True
>>> s.save()
2013-01-04 13:02:04,055 (0.001) INSERT INTO "m2m_test_objecta" ("uuid") VALUES (foo); args=['foo']
<ObjectA: ObjectA object>

But with ObjectBSerializer:

>>> s = ObjectBSerializer(data={"uuid": "foo"})
>>> s.is_valid()
True
>>> s.save()
2013-01-04 13:02:29,182 (0.000) SELECT (1) AS "a" FROM "m2m_test_objectb" WHERE "m2m_test_objectb"."uuid" =   LIMIT 1; args=('',)
2013-01-04 13:02:29,182 (0.000) INSERT INTO "m2m_test_objectb" ("uuid") SELECT  AS "uuid"; args=('',)
<ObjectB: ObjectB object>
>>> ObjectB.objects.all()[0].uuid
2013-01-04 13:03:23,190 (0.000) SELECT "m2m_test_objectb"."uuid" FROM "m2m_test_objectb" LIMIT 1; args=()
u''

So, is it someway possible to specify the primary key value in the serialized data ?

Also I don't feel that it should save ObjectB with an empty string in the primary_key as there is no blank=True or null=True in the model definition.

Casey Crites

unread,
Jan 9, 2013, 1:54:14 AM1/9/13
to django-res...@googlegroups.com
See here: https://github.com/tomchristie/django-rest-framework/issues/563

You should be able to explicitly declare the uuid field on ObjectBSerializer and set read_only=False.

Tom Christie

unread,
Jan 12, 2013, 4:55:24 AM1/12/13
to django-res...@googlegroups.com
Now fixed in master.
Reply all
Reply to author
Forward
0 new messages