[英]Create JSON fixture for django models
I have defined model as below: 我已经定义了如下模型:
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'
Now I want to update models with "loaddata" command from JSON file. 现在,我想使用JSON文件中的“ loaddata”命令更新模型。 I have a JSON file in the format below: 我有以下格式的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"
},
when I used "manage.py loaddata" command i got 当我使用“ manage.py loaddata”命令时
error : "User has no field named u'VideoData'"
How can I update the fields? 如何更新字段?
I recommend to update your models so that they become related to each other. 我建议您更新模型,以使它们彼此关联。
For example,to the User
model add a many-to-many relationship, possibly with a through table
to hold the attributes of such relationship (eg when it was rented/watched by the user) 例如,向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()
See here for more details. 有关更多详细信息,请参见此处 。
Obviously you can insert the many-to-many relationship in the VideoData class instead of inside the User class. 显然,您可以在VideoData类中而不是User类中插入多对多关系。
Create your objects in the DB, then dump them into JSON with django-admin-dumpdata 在数据库中创建对象,然后使用django-admin-dumpdata将其转储为JSON
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.