为django模型创建JSON fixture

时间:2015-07-10 15:00:42

标签: python json django django-rest-framework

我已经定义了如下模型:

model.py

class User(models.Model):
    user_id = models.IntegerField()
    user_name = models.CharField(max_length=40)
    email = models.EmailField()
    city = models.CharField(max_length=40)
    class Meta:
        ordering = ['user_id']
        verbose_name = 'User MetaData'
        verbose_name_plural = 'Users MetaData'
    def __unicode__(self):
        return str(self.user_id)

class VideoData(models.Model):
    video = models.CharField(max_length=40)
    time  = models.IntegerField()
    user = models.ForeignKey(User)
    class Meta:
        verbose_name = 'User_Video MetaData'
        verbose_name_plural = 'Users_Video MetaData'

现在我想用JSON文件中的“loaddata”命令更新模型。我有一个以下格式的JSON文件:

{  
  "fields":{  
     "user id":12026,
     "user name":"Paul Graham",
     "email":"pgraham0@sun.com",
     "city":"China",
     "VIdeoData":[  
        {  
           "video":"Livetube",
           "time":0
        },
        {  
           "video":"Leexo",
           "time":22
        }
     ]
  },
  "pk":1,
  "model":"graph.user"
},

当我使用“manage.py loaddata”命令时,我得到了

error : "User has no field named u'VideoData'"

如何更新字段?

1 个答案:

答案 0 :(得分:1)

我建议您更新模型,使它们彼此相关。

例如,向User模型添加多对多关系,可能使用through table来保存此类关系的属性(例如,当用户租用/观看时)

class User(models.Model):
    user_id = models.IntegerField()

    videos = models.ManyToManyField(VideoData, through='VideoRenting', through_fields=('user', 'videodata'))

    user_name = models.CharField(max_length=40)
    email = models.EmailField()
    city = models.CharField(max_length=40)
    class Meta:
        ordering = ['user_id']
        verbose_name = 'User MetaData'
        verbose_name_plural = 'Users MetaData'
    def __unicode__(self):
        return str(self.user_id)

class VideoRenting(models.Model):
    user = models.ForeignKey(User)
    videodata = models.ForeignKey(VideoData)
    rented_at = models.DateTimeField()

有关详细信息,请参阅here

显然,您可以在VideoData类中插入多对多关系,而不是在User类中插入。

在数据库中创建对象,然后使用django-admin-dumpdata

将它们转储到JSON中