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.

3
  • Possible duplicate of How to make an auto increment integer field Django Commented May 22, 2018 at 16:02
  • @Take_Care_ no, because i can't use this "number" field as primary key. Commented May 22, 2018 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. Commented May 22, 2018 at 16:14

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.