首页 > 解决方案 > 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}"

标签: pythondjangooopdjango-modelsdjango-queryset

解决方案


您可以先尝试获取或创建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"],
               ...
               ...
    

推荐阅读