将嵌套字典数据保存到django模型的方法

时间:2015-06-15 11:38:57

标签: python django

我的字典

{
id : 123
"data":{
    "name" : "sample name"
    "description" : "sample discriptio"
    "address":{
        "address": {
            "h.no" : '420'
            "streat": 'some streat'
        }
        "city" : "Hyd"
        "State" : "S"
        "Country": "xyz"
    }
    "geoLocation":{
        "latitude": 40.0000,
        "longitude": -118.0000

    }
    "links":
    [
        {"rel": "image", "url":"http://image.com/1.jpg"},
        {"rel": "image", "url":"http://image.com/2.jpg"},
        {"rel": "some other", "url":"http://some/other/url"},
    ]

}
}

这是我的模特:

class my_model(models.Model):
    name = models.CharField(max_length=255)
    latitude = models.DecimalField(max_digits=55, decimal_places=20)
    description = models.TextField()
    longitude = models.DecimalField(max_digits=55, decimal_places=20)
    h_no = models.CharField(max_length=255)
    streat = models.CharField(max_length=255, blank=True)
    city = models.CharField(max_length=55)
    state = models.CharField(max_length=25)
    postal = models.CharField(max_length=25)
    country = models.CharField(max_length=25)
    currency = models.CharField(max_length=25)  
    updatedOn = models.DateTimeField(auto_now=True)
    images_links = models.ManyToManyField(rental_images)

    def __unicode__(self):
        return self.name

Add_or_Update_view逻辑:

instance = mymodel.objects.get_or_create(id=id)
for key,value in data['data'].items():

    field = mymodel._meta.get_field(key)
    if not field:
        continue
    if isinstance(field, models.ManyToManyField):
        # to handle ManyToManyField fields, like skils ['java', python]
    elif isinstance(field, models.ForeignKey) and hasattr(value, 'items'):
        # to handle ForeignKey fields
        setattr(instance, key, rel_instance)
    else:
        setattr(instance, key, value)
instance.save()

data['data'].items()无法获取所有子dict键,setattr(instance, key, value)中的值可用于h_no,streat,latitude,longitude等字段(这些值在嵌套字典中)。

上面的字典有链接列表,我希望保存所有'rel':'image'我的images = models.ManyToManyField(images_model)

有没有最好的方法可以直接将日期保存到django模型。 以及如何在保存数据的同时处理模型关系。

0 个答案:

没有答案