2017-07-14 59 views
0

是否可以使用get_or_create動態創建/獲取傳遞字典的字典,其中某些字段不會像示例中那樣存在?Django - 使用字典獲取或創建動態對象

什麼是最好的方式來做這樣的事情?

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) 

回答

0

你可以做到這一點幾乎是你發佈方式,僅改變多對多領域:

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