3

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.

Vitali Skripka
  • 562
  • 1
  • 7
  • 25
  • Possible duplicate of [How to make an auto increment integer field Django](https://stackoverflow.com/questions/21128899/how-to-make-an-auto-increment-integer-field-django) – Take_Care_ May 22 '18 at 16:02
  • @Take_Care_ no, because i can't use this "number" field as primary key. – Vitali Skripka May 22 '18 at 16:05
  • each model in django has by default its `id` and `pk` fields, co u can call one of them even if u didn't set AutoField manually. – Chiefir May 22 '18 at 16:14

2 Answers2

3

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)
Shivam Singh
  • 1,584
  • 1
  • 10
  • 9
0

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)
Community
  • 1
  • 1
USS1994
  • 594
  • 1
  • 5
  • 16