我有一个帖子模型和一个postImage模型:
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.foreignKey
中的PostResource
行,它就可以了。如果我浏览到api/v1/postImage/?format=json
,则不会显示任何错误,只会显示一个空集合。
答案 0 :(得分:2)
试试这个:
class PostResource(ModelResource):
images = fields.OneToManyField(PostImageResource, 'images', full=True)
class Meta:
queryset = Post.objects.all()
resource_name = 'post'
-------编辑-------
嗯...
在你的模特中:
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。