Django - 使用字典获取或创建动态对象

时间:2017-07-14 15:03:06

标签: django

是否可以使用get_or_create动态创建/获取传递字典的对象,其中某些字段不会像示例中那样出现?

做这样的事情最好的方法是什么?

class Car(models.Model):
    id = models.CharField(max_length=255)
    name = models.CharField(max_length=255, null=True)
    brand = models.CharField(max_length=255)

    drivers = models.ManyToManyField(Driver, related_name='cars')

class Driver(models.Model):
    name = models.CharField(max_length=255)

################
driver = Driver.objects.create(id='foo')
for row in cars:
     # Dictionary might be {'id': foo, 'brand': ford} so without a name field
     dictionary = {
       key:value
       for key,value in row
       if value is not None
     }

     # Passing the dictionary with keys/fields values/values
     car_object, created = Car.objects.get_or_create(driver, **dictionary)

1 个答案:

答案 0 :(得分:0)

您几乎可以按照发布的方式执行此操作,只需将多个字段更改为多个字段:

car_object, created = Car.objects.get_or_create(**dictionary)
car_object.drivers.add(driver)