【问题标题】:Add number field to Django model将数字字段添加到 Django 模型
【发布时间】:2018-11-01 11:22:43
【问题描述】:

我有一个 django 电影模型

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)

我需要使用movie_id 作为主键,但我还需要一个字段,它表示表中项目的行数。 它必须自动递增,就像标准的“id”字段一样。 我怎样才能添加它?

这个问题https://stackoverflow.com/users/3404040/take-care 类似,但我不能使用我的“数字”字段作为主键,因为movie_id 已经用于此。

【问题讨论】:

  • @Take_Care_ no,因为我不能使用这个“数字”字段作为主键。
  • django 中的每个模型默认都有 idpk 字段,即使您没有手动设置 AutoField,您也可以调用其中一个。

标签: python django


【解决方案1】:

您可以使用类似的东西,但如果您不想使用默认的id 字段,它可能会消耗资源。

class Film(models.Model):
    def number():
        no = Film.objects.count()
        return no + 1

    movie_row = models.IntegerField(unique=True,default=number)

【讨论】:

    【解决方案2】:

    来自Django's Documentation

    默认情况下,Django 为每个模型提供以下字段:

    id = models.AutoField(primary_key=True)

    这是一个自动递增的主键。

    如果您想指定自定义主键,只需在其中一个字段上指定 primary_key=True。如果 Django 看到你明确设置了 Field.primary_key,它不会添加自动 id 列。

    每个模型只需要一个字段来设置 primary_key=True(显式声明或自动添加)。

    如果你想让你的名字被明确称为movie_id,你可能需要这样的东西:

    class Film(models.Model):
        movie_id = models.AutoField(primary_key=True)
    

    【讨论】:

      猜你喜欢
      • 2018-05-25
      • 1970-01-01
      • 2018-08-03
      • 1970-01-01
      • 2021-08-30
      • 2011-06-11
      • 2014-04-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多