1

我有一个 post 模型和一个 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()

我为两者创建了美味的资源:

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,则不会显示任何错误,只是一个空集合。

4

1 回答 1

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 和 blank=True。

于 2012-07-12T21:14:20.750 回答