如何让Django模型中的id自动加2?

mrh*_*oji 5 mysql django django-models

既然MySQL中的auto_increment设置是针对全局的,那不能设置到特定的表吗?

我正在考虑是否可以在Django的模型中使id自动增加2?

模型.py

class Video(models.Model):
    name = model.CharField(max_length=100, default='')
    upload_time = models.DateTimeField(blank=True, null=True)

    def __str__(self):
        return self.name
Run Code Online (Sandbox Code Playgroud)

我应该怎么办?谢谢你的帮助。

JPG*_*JPG 3

你可以用save()我的模型的最重要方法来做

from django.db.models import Max, F


class Video(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=100, default='')
    upload_time = models.DateTimeField(blank=True, null=True)

    def save(self, *args, **kwargs):
        if not self.pk:
            max = Video.objects.aggregate(max=Max(F('id')))['max']
            self.id = max + 2 if max else 1 # if the DB is empty
        super().save(*args, **kwargs)

    def __str__(self):
        return self.name
Run Code Online (Sandbox Code Playgroud)