2012-07-12 91 views
1

我有一個樁模型和postImage型號:Django的tastypie外鍵的麻煩

class PostImage(models.Model): 
    post = models.ForeignKey(Post, related_name="images") 
    # @@@@ figure out a way to have image folders per user... 
    image = models.ImageField(upload_to='images') 
    description = models.CharField(max_length=100) 
    order = models.IntegerField() 

我創建tastypie資源兩種:

class PostImageResource(ModelResource): 
    class Meta: 
     queryset = PostImage.objects.all() 
     resource_name = 'postImage' 


class PostResource(ModelResource): 
    images = fields.ForeignKey(PostImageResource, 'images', full=True) 
    class Meta: 
     queryset = Post.objects.all() 
     resource_name = 'post' 

當我嘗試瀏覽api/v1/post/?format=json我得到出現以下錯誤:

The object '' has an empty attribute 'image' and doesn't allow a default or null value. 

我還沒有任何PostImages呢。

如果我擺脫images = fields.foreignKeyPostResource,它的工作原理。如果我瀏覽到api/v1/postImage/?format=json,則不顯示錯誤,只是一個空集合。

+0

你是否檢查過你的所有PostImage對象都填充了'image'字段? – Lycha 2012-07-12 21:08:17

+0

我還沒有任何PostImage對象。我希望能夠在沒有圖像的情況下發布帖子。 – AlexBrand 2012-07-12 21:20:23

回答

2

試試這個:

class PostResource(ModelResource): 
    images = fields.OneToManyField(PostImageResource, 'images', full=True) 
    class Meta: 
     queryset = Post.objects.all() 
     resource_name = 'post' 

------- ------- EDITED

嗯......

在你的模型:

class PostImage(models.Model): 
    post = models.ForeignKey(Post, related_name="images") 
    image = models.ImageField(upload_to='images', null=True, blank=True) 
    description = models.CharField(max_length=100) 
    order = models.IntegerField() 

注意null = True且空白= True。

+0

fields.ForeignKey與fields.OneToManyField – AlexBrand 2012-07-12 21:20:45

+1

@alexBrand no相同。 ForeignKey擴展ToOneField和OneToManyField擴展ToManyField =] – 2012-07-12 21:23:52