Add numeric fields to the Django model… here is a solution to the problem.
Add numeric fields to the 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 the primary key, but I also need a field that represents the number of rows for the item in the table.
It must be automatically incremented, just like the standard “id” field.
How can I add it?
The problem is similar https://stackoverflow.com/users/3404040/take-care But I can’t use my Number field as a primary key because movie_id is already used for this purpose.
Solution
You can use
something like this, but it can consume resources if you don’t 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)