python - Django 中 .get_or_create 函数的响应不正确
问题描述
我一直试图理解为什么我使用的 .get_or_create 函数不起作用。它应该在数据库中找到具有匹配参数的对象,如果没有找到则创建一个新对象。运行它时,它总是说没有匹配的对象,并且元组每次都返回 True 因此总是创建一个新对象(重复)。
这会导致 except 语句也每次都运行。
这是我的功能:
for desktop in desktops:
try:
clean_location = serialized_location_information(desktop)
clean_machine = serialize_machine_information(desktop)
location_name, location_created = Location.objects.get_or_create(
latitude=clean_location["latitude"],
longitude=clean_location["longitude"],
provider=clean_machine["provider"],
defaults={
"country": clean_location["country"],
"state": clean_location["state"],
"city": clean_location["city"],
"street_address": clean_location["street_address"],
"postal_code": clean_location["postal_code"],
"name": clean_location["name"],
"status": clean_location["status"],
}
)
if location_created:
logger.info(f"New Location was created successfully")
except Exception as ex:
logger.error(f"Could not get or create location: {ex}")
location = None
pass
这是我的模型:
class Location(models.Model):
class Meta:
unique_together = ['latitude','longitude','provider']
latitude = models.DecimalField(max_digits=9, decimal_places=6)
longitude = models.DecimalField(max_digits=9, decimal_places=6)
country = models.CharField(max_length=100, blank=True)
state = models.CharField(max_length=25, blank=True)
city = models.CharField(max_length=250, blank=True)
street_address = models.CharField(max_length=250, blank=True)
postal_code = models.CharField(max_length=100, blank=True)
name = models.TextField(blank=True)
status = models.PositiveSmallIntegerField(default=10, choices=LocationStatus.CHOICES)
provider = models.ForeignKey(Provider, on_delete=models.CASCADE, default= '')
def __str__(self):
return f"{self.name}"
解决方案
您可以先尝试获取或创建provider
对象,然后查找 Location 对象,如下所示:-
for desktop in desktops:
try:
clean_location = serialized_location_information(desktop)
clean_machine = serialize_machine_information(desktop)
provider, _ = Provide.objects.get_or_create(provider_name = clean_machine["provider"])
location_name, location_created = Location.objects.get_or_create(
latitude=clean_location["latitude"],
longitude=clean_location["longitude"],
provider=provider,
defaults={
"country": clean_location["country"],
"state": clean_location["state"],
"city": clean_location["city"],
...
...
推荐阅读
- java - 插入关系表时,房间多对多关系 UNIQUE 约束失败
- sql - 无法在 BigQuery 中选择列
- xquery - 如何在不同元素中的数据的构面内获取单行数据
- python - 如何将项目附加到对象数组?
- c# - 散列密码显示奇怪
- javascript - PHP:如何先使用变量,然后在 PHP 中初始化它(使用 Jquery 或 Ajax)?
- python - AWS Glue 调用 o128.resolveChoice 时出错
- r - 从 github 安装 flipMaxDiff 包时出错
- sql - “在不存在的地方插入”是否包括在同一插入处插入的记录
- iot - LoRaWAN 规划 - M 个网关是否足以满足 N 个传感器和 1 个 [msg/hr] 的需求?