1

I have a post model and a postImage model:

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()

I have created tastypie resources for both:

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'

When I try to browse to api/v1/post/?format=json I get the following error:

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

I don't have any PostImages yet.

If I get rid of the images = fields.foreignKey line in PostResource, it works. If I browse to api/v1/postImage/?format=json, no error is shown, just an empty collection.

2
  • Have you checked that all of your PostImage objects have populated the image field?
    – Lycha
    Jul 12, 2012 at 21:08
  • I don't have any PostImage objects yet. I want to be able to have Posts without images.
    – AlexBrand
    Jul 12, 2012 at 21:20

1 Answer 1

2

Try this:

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

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

Hmm...

In Your model:

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()

Note null=True and blank=True.

2
  • fields.ForeignKey is the same as fields.OneToManyField
    – AlexBrand
    Jul 12, 2012 at 21:20
  • 1
    @alexBrand no. ForeignKey extends ToOneField and OneToManyField extends ToManyField =] Jul 12, 2012 at 21:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.