Ethan
Ethan

Reputation: 747

How to add entry having to lookup foreign key ID

I have multiple locations defined in my DB. For example purposes, say I have "Mimai" as a city. I am trying to understand how I add a Measurment entry and reference the Location ID for the city "Miami" in Location. Each Location will have many Measurements.

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)

Question #1 Would I do?

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.id
)

Question #2 There should only be 1 Measurement per day for each Location. In the event a Measurement is added twice with the same date, I take update_or_create would update cpu_util if the value was different?

Upvotes: 0

Views: 39

Answers (1)

HenryM
HenryM

Reputation: 5793

Question 1: Both work (notice the change)

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
)

Question 2: Add unique_together to your model

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')

Upvotes: 1

Related Questions