【问题标题】:Incorrect response from .get_or_create function in DjangoDjango 中 .get_or_create 函数的响应不正确
【发布时间】:2021-12-08 14:38:13
【问题描述】:

我一直试图了解为什么我使用的 .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}"

【问题讨论】:

  • 我觉得你打错了,if l_created: 试试改成if location_created:
  • 您在clean_machine["provider"] 中传递的值是对象还是字符串?
  • 值为字符串

标签: python django oop django-models django-queryset


【解决方案1】:

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

【讨论】:

  • 这不起作用,因为有多个对象具有相同的提供者
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-03
  • 1970-01-01
  • 2010-12-28
  • 1970-01-01
  • 2017-10-18
  • 1970-01-01
相关资源
最近更新 更多