Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What means the serialize=False on Primary-key field?

I didn't found in the Django docs and Source Code the reason for serialize=False on primary key fields. Is there a special reason to set it?

Thanks

like image 606
Azd325 Avatar asked Feb 14 '17 15:02

Azd325


1 Answers

Azd325,

it is as simple as it sounds, this field will not be part of the serialized object..

Although, I guess your question concerns to models that are being migrated and have a generated ID with serialize=False, right? such as in here.. There isn't really a documentation on this because it is Django's engine trick to create an intrinsic ID since you decided not to declare an explicit ID for your object..

Some additions of tests I just made

Create a model without an explicit ID

class Model1Test(models.Model):
    justafield = models.CharField(max_length=1000)

Migration results

class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Model1Test',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('justafield', models.CharField(max_length=1000)),
            ],
        ),
    ]

Database-level script

CREATE TABLE public.module1_model1test
(
  id integer NOT NULL DEFAULT nextval('module1_model1test_id_seq'::regclass),
  justafield character varying(1000) NOT NULL,
  CONSTRAINT module1_model1test_pkey PRIMARY KEY (id)
)

Some good reasons to do that from Quassnoi:

  1. You need your table to be joinable on something
  2. If you want your table to be clustered, you need some kind of a primary key
  3. If your table design does not need a primary key, rethink your design: most probably, you are missing something. Why keep identical records?
like image 124
bobleujr Avatar answered Oct 19 '22 21:10

bobleujr