Django 使用OneToMany添加到模型并更新现有条目。
我有几个Django模型问题。我将以下代码作为Django管理扩展运行,这是我的新手 1) 我不确定我的“Location.objects.get(city=key)”是否适用于我的将\u server\u添加到\u db功能中的OneToMany。我怀疑这是不对的 2) 我如何加强这一点,以便如果执行两次,它将更新现有的服务器条目而不是出错 Django服务器型号:Django 使用OneToMany添加到模型并更新现有条目。,django,django-models,Django,Django Models,我有几个Django模型问题。我将以下代码作为Django管理扩展运行,这是我的新手 1) 我不确定我的“Location.objects.get(city=key)”是否适用于我的将\u server\u添加到\u db功能中的OneToMany。我怀疑这是不对的 2) 我如何加强这一点,以便如果执行两次,它将更新现有的服务器条目而不是出错 Django服务器型号: class Servers(models.Model): name = models.CharField((
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)
class Location(models.Model):
city = models.CharField(('city'), max_length=10)
geolocation = models.PointField(('location'))
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()
Django位置模型:
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)
class Location(models.Model):
city = models.CharField(('city'), max_length=10)
geolocation = models.PointField(('location'))
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()
功能:
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)
class Location(models.Model):
city = models.CharField(('city'), max_length=10)
geolocation = models.PointField(('location'))
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()
谢谢 我不明白你的问题1;这句话没有错,而且在任何情况下都没有“一对多”的具体含义 要防止每次都创建新条目,应使用: 此后无需调用
save()