外键返回对象而不是整数

时间:2020-05-18 01:13:17

标签: django-models

在“ models.py”中

df <- structure(list(Lima = c(1L, 6L, 6L, 8L, 9L, 11L), Arequipa = c(NA, 
NA, 1L, 2L, 3L, 4L), Huánuco = c(NA, NA, NA, 5L, 7L, 8L)), 
  class = "data.frame", row.names = c("1", 
"2", "3", "4", "5", "6"))

在“ admin.py”中

class Run(models.Model):
    number = models.IntegerField(choices=((int(x), x) for x in range(1, 50)))
    type = models.CharField(max_length=10, choices=((str(x), x) for x in ['bit', 'casing']))
    run_date = models.DateTimeField(default=timezone.now)
    well = models.ForeignKey(Well, related_name='run', on_delete=models.CASCADE)
    created_by = models.ForeignKey(User, related_name='run_created_by', null=True, on_delete=models.SET_NULL)
    description = models.CharField(max_length=255)

    class Meta:
        verbose_name = "Run Information"
        verbose_name_plural = "Run Information"

    def __int__(self):
        return self.number

class BitRun(models.Model):
    number = models.PositiveSmallIntegerField(choices=((int(x), x) for x in range(1, 50)))
    od = models.DecimalField(max_digits=5, decimal_places=3)
    inner_diameter = models.DecimalField(max_digits=5, decimal_places=3)
    tfa = models.DecimalField(max_digits=5, decimal_places=3)
    bottom_depth = models.DecimalField(max_digits=7, decimal_places=2)
    top_depth = models.DecimalField(max_digits=7, decimal_places=2)
    run = models.ForeignKey(Run, related_name='bit_number', on_delete=models.CASCADE)
    well = models.ForeignKey(Well, related_name='well_name', on_delete=models.CASCADE)

    class Meta:
        verbose_name = "Bit Record"
        verbose_name_plural = "Bit Records"

I see run object(1) instead of the actual fields value.

有人可以指出我在代码中做错了什么吗? 谢谢

1 个答案:

答案 0 :(得分:0)

为每个模型添加__str__表示形式。

def __str__(self):
    rerurn f"{self.field_name}"

field_name必须是您要查看的字段名称。