Django模型:将默认IntegerField设置为实例数

2024-10-05 12:17:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我想将我的成就模型的“order”整数字段设置为成就中对象的当前计数。order字段用于对成果进行排序,用户可以对其进行更改。现在我默认为1。在

class Achievement(models.Model):
    title = models.CharField(max_length=50, blank=True)
    description = models.TextField()
    order = models.IntegerField(default=1)   #Get the number of achievement objects
    class Meta:
        db_table = 'achievement'
        ordering = ['order', 'id']

例如,如果我的数据库中已经有一个成就,不管顺序如何,下一个应该得到order=2。在


Tags: 对象用户模型model排序titlemodelsorder
1条回答
网友
1楼 · 发布于 2024-10-05 12:17:04

据我所知,您希望在order整型字段中有一个默认值1,并将其与Achievment的每个条目一起递增(功能与id相同),但也允许用户更改它。在

为此,您可以使用Django的^{}

An IntegerField that automatically increments according to available IDs. You usually won’t need to use this directly; a primary key field will automatically be added to your model if you don’t specify otherwise.

像这样:

class Achievement(models.Model):
    ...

    order = models.AutoField(default=1, primary_key=False)
    # Also specify that this autofield is *not* a ^ primary key

    class Meta:
        ordering = ['order', 'id']

相关问题 更多 >

    热门问题