how to create primary key automatically when creating model objects in database from views.py

时间:2019-05-19 03:56:20

标签: django

i have a model and i m trying to create an instance of that model in db from the views.py , as it has one primary key , how to auto-create or make it an auto functionality to assign value to that primary-key?

in my case it is table_id in ActionLog model

models.py

  class ActionLog(models.Model):
      table_id = models.IntegerField(primary_key=True)
      admin_id = models.IntegerField()
      timestamp = models.DateTimeField()
      parameter = models.CharField(max_length=150)

views.py

 def admin_view(request):
    access_log = ActionLog()
    access_log.admin_id = request.session['admin_id']
    access_log.timestamp = datetime.now()
    access_log.parameter = "log-in"

1 个答案:

答案 0 :(得分:0)

A primary key is auto-generated. You don't need this to do manually.

def admin_view(request):
    ...
    access_log.save()

By calling save() method, an object is saved to the database and generate a pk. You can see the primary key value for the last saved object by this

def admin_view(request):
    ...
    access_log.save()
    print(access_log.pk)

If you want this in model level auto increment the pk value

table_id = models.AutoField(primary_key=True)