How to disable automatic id creation in Django?
Asked Answered
W

1

8

I want to disable automatic id creation in Django Models. Is it possible to do so? How?

Wigley answered 17/10, 2015 at 15:49 Comment(2)
Declare a primary key on your model (docs.djangoproject.com/en/1.8/ref/models/fields/#primary-key). Models without IDs aren't supported (AFAIK)Quaint
Yeah that's possible. But what if I just want to store the like of a user for an item? I don't need id for that stuff.Wigley
N
6

As mentioned in the reply, you need to declare a primary key on a non-AutoField. For example:

from django.db import models

class Person(models.Model):
    username = CharField(primary_key=True, max_length=100)
    first_name = CharField(null=True, blank=True, max_length=100)

Please note, setting a field to primary_key=True automatically makes it unique and not null. Good luck!

Naivete answered 17/10, 2015 at 23:46 Comment(3)
Yeah that's possible. But what if I just want to store the like of a user for an item? I don't need id for that stuff.Wigley
Right, you may have use-cases where in your database tables you wouldn't go with 3rd form of normalisation, but if you need those tables to be exposed in Django as models, you have to. There is little / no loss from your side, these fields can be auto-managed and you would hardly argue about the used space ...Quaint
It isn't even really exposed to you as a coder unless you view it in the database, and minuscule overhead for a lot of reliability. Having a guaranteed unique key in a DB has saved my butt over the years more times than I can count.Naivete

© 2022 - 2024 — McMap. All rights reserved.