EthanB
EthanB

Reputation: 159

Adding to model with OneToMany and updating existing entries.

I have a couple of Django model questions. I am running the following code as a Django manage extension, which I am new to.

1) I am not certain my "Location.objects.get(city=key)" is correct for OneToMany in my add_server_to_db function. I suspect this is incorrect?

2) How can I harden this so if this is executed twice, it will update existing Server entries vs. error out?

Django Server Model:

class Servers(models.Model):
    name       = models.CharField(('name'), max_length=128)
    location   = models.OneToOneField('locations.Location', on_delete=models.CASCADE)
    ip_address = models.CharField(('ip_address'), max_length=128)
    date       = models.DateField(auto_now=True)

Django Location Model:

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

Function:

def add_server_to_db(data_dict):
    print(data_dict)
    for key, val in data_dict.items():
        loc = Location.objects.get(city=key)
        m = Server(
             location=loc,
             name=val['name'],
             ip_address=val['ip_address'],
        m.save()

Thanks.

Upvotes: 0

Views: 25

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599600

I don't understand your question 1; there's nothing wrong with that line, and nothing specific to "one-to-many" in any case.

To prevent this creating new entries every time, you should use update_or_create:

loc = Location.objects.get(city=key)
Server.objects.update_or_create(
     location=loc,
     defaults={'name': val['name'], 'ip_address': val['ip_address']}
)

There's no need to call save() after this.

Upvotes: 1

Related Questions