Vitali Skripka
Vitali Skripka

Reputation: 632

Add number field to Django model

I have a django movie model

class Film(models.Model):

    title = models.CharField(max_length=200)
    movie_id = models.CharField(max_length=8, unique=True, primary_key=True)
    director = models.ForeignKey('Director', on_delete=models.SET_NULL, null=True)
    year = models.IntegerField(null=True)
    genres = models.ManyToManyField(Genre)

I need to use movie_id as primary key, but also i need a field, which represents number of item's row in table. It must increment automatically, just like standard "id" field. How can i add it?

This question https://stackoverflow.com/users/3404040/take-care is similar, but i can't use my "number" field as primary key, because movie_id is already used for that.

Upvotes: 3

Views: 4241

Answers (2)

Shivam Singh
Shivam Singh

Reputation: 1624

You can use something like this, but it can be resource consuming if you do not want to use the default id field.

class Film(models.Model):
    def number():
        no = Film.objects.count()
        return no + 1

    movie_row = models.IntegerField(unique=True,default=number)

Upvotes: 3

USS1994
USS1994

Reputation: 614

From Django's Documentation:

By default, Django gives each model the following field:

id = models.AutoField(primary_key=True)

This is an auto-incrementing primary key.

If you’d like to specify a custom primary key, just specify primary_key=True on one of your fields. If Django sees you’ve explicitly set Field.primary_key, it won’t add the automatic id column.

Each model requires exactly one field to have primary_key=True (either explicitly declared or automatically added).

If you want yours to explicitly be called movie_id you probably need something like:

class Film(models.Model):
    movie_id = models.AutoField(primary_key=True)

Upvotes: 0

Related Questions