2015-07-10 104 views
0

我已經定義的模型如下創建JSON夾具:的Django模型

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":"[email protected]", 
    "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

這是正確的,因爲'VideoData'是不是在用戶模式的字段。通常,模型不遵循封裝,但通過[關係](https://docs.djangoproject.com/en/dev/topics/db/models/)互相引用(即一對一,一對一,許多,多對多) – Pynchia

回答

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類中。

在數據庫中創建對象,然後將它們放到JSON與django-admin-dumpdata