如何添加必须查找外键ID的条目

时间:2018-05-06 04:02:26

标签: python django django-models

我的数据库中定义了多个位置。例如,我说“Mimai”是一个城市。我想了解如何添加 Measurment 条目并引用位置中城市“Miami”的位置ID 。每个位置都会有多个度量

class Location(models.Model):
    city = models.CharField(('city'), max_length=20)
    geolocation = models.PointField(('location'))

class Measurement(models.Model):
    server      = models.CharField(('server'), max_length=10)
    cpu_util    = models.CharField(('cpu'), max_length=10)
    date        = models.DateField(default=timezone.now)
    location    = models.ForeignKey(Location, on_delete=models.CASCADE)

问题#1 我会这样做吗?

m = Measurement.objects.update_or_create(
    server      = "Bubba",
    cpu_util    = "100%",
    location    = Location.objects.get(city="Miami")
)

或(如果可能的话?)

l = Location.objects.get(city="Miami")
m = Measurement.objects.update_or_create(
    server      = "Bubba",
    cpu_util    = "100%",
    location    = l.id
)

问题#2 每个位置每天应该只有1 度量。如果度量在相同日期添加两次,我认为如果值不同,update_or_create会更新 cpu_util 吗?

1 个答案:

答案 0 :(得分:1)

问题1 :两者都有效(注意更改)

m = Measurement.objects.update_or_create(
    server      = "Bubba",
    cpu_util    = "100%",
    location    = Location.objects.get(city="Miami")
)
Or (if this is possible?)

l = Location.objects.get(city="Miami")
m = Measurement.objects.update_or_create(
    server      = "Bubba",
    cpu_util    = "100%",
    location    = l
)

问题2 :将unique_together添加到您的模型

class Measurement(models.Model):
    server      = models.CharField(('server'), max_length=10)
    cpu_util    = models.CharField(('cpu'), max_length=10)
    date        = models.DateField(default=timezone.now)
    location    = models.ForeignKey(Location, on_delete=models.CASCADE)

    class Meta:
        unique_together = ('location','date')