在django tastypie中使用OneToOneField创建对象

时间:2012-08-01 09:12:04

标签: python django tastypie

我有两个模型:Project和Album。它们通过oneToOneField相互关联。

相册/ models.py:

class Album(models.Model):
    title = models.CharField(_('title'), max_length=128)
    slug = models.SlugField(_('slug'), unique=True, default='main-gallery')

项目/ models.py

class Project(models.Model):
    title = models.CharField(_('title'), max_length=300)
    slug = models.SlugField(_('slug'), unique=True)

    main_gallery = models.OneToOneField(Album, verbose_name=_('related main album'), related_name='project', unique=True)

@receiver(pre_save, sender=Project)
def create_project(sender, instance=None, **kwargs):
    if instance is None:
    try:
        str(instance.main_gallery)
    except Album.DoesNotExist:
        main_gallery = Album.objects.create(title=''.join((instance.title, ' - ', 'main gallery')))

如果创建了项目,也会为其创建相册。这很好用。但是当我尝试使用django tastypie在我的api中创建一个时它不会工作:

class AlbumResource(ModelResource):
    class Meta:
        queryset = Album.objects.all()
        resource_name = 'album'
        #fields = ['title','slug',]

    def dehydrate_resource_uri(self, bundle):
        return bundle.data['slug']

class ProjectResource(ModelResource):
    main_gallery = fields.OneToOneField(AlbumResource, 'main_gallery', related_name='project', full=False)
    class Meta:
        queryset = Project.objects.all()
        resource_name = 'project'
        fields = ['slug', 'title', 'main_gallery']

        authorization= Authorization()

        allowed_methods = ['get', 'post', 'put']

def obj_create(self, bundle, request=None, **kwargs):
    logger.debug("obj_create Bundle %s" % bundle)
    return super(ProjectResource, self).obj_create(bundle, request, created_by=request.user)

虽然Project API端点上的“GET”有效,但当我尝试在“POST”上创建新的Project时,我收到以下错误:

    Traceback (most recent call last):
  File "/Users/PATHvenv/lib/python2.7/site-packages/django/core/handlers/base.py", line 111, in get_response
    response = callback(request, *callback_args, **callback_kwargs)
  File "/Users/PATHvenv/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 77, in wrapped_view
    return view_func(*args, **kwargs)
  File "/Users/PATHvenv/lib/python2.7/site-packages/tastypie/resources.py", line 192, in wrapper
    response = callback(request, *args, **kwargs)
  File "/Users/PATHvenv/lib/python2.7/site-packages/tastypie/resources.py", line 397, in dispatch_list
    return self.dispatch('list', request, **kwargs)
  File "/Users/PATHvenv/lib/python2.7/site-packages/tastypie/resources.py", line 427, in dispatch
    response = method(request, **kwargs)
  File "/Users/PATHvenv/lib/python2.7/site-packages/tastypie/resources.py", line 1165, in post_list
    updated_bundle = self.obj_create(bundle, request=request, **self.remove_api_resource_names(kwargs))
  File "/Users/PATH/path/path/apps/api/resources.py", line 70, in obj_create
    return super(ProjectResource, self).obj_create(bundle, request, created_by=request.user)
  File "/Users/PATHvenv/lib/python2.7/site-packages/tastypie/resources.py", line 1774, in obj_create
    bundle = self.full_hydrate(bundle)
  File "/Users/PATHvenv/lib/python2.7/site-packages/tastypie/resources.py", line 698, in full_hydrate
    value = field_object.hydrate(bundle)
  File "/Users/PATHvenv/lib/python2.7/site-packages/tastypie/fields.py", line 636, in hydrate
    value = super(ToOneField, self).hydrate(bundle)
  File "/Users/PATHvenv/lib/python2.7/site-packages/tastypie/fields.py", line 154, in hydrate
    elif self.attribute and getattr(bundle.obj, self.attribute, None):
  File "/Users/PATHvenv/lib/python2.7/site-packages/django/db/models/fields/related.py", line 343, in __get__
    raise self.field.rel.to.DoesNotExist
DoesNotExist

1 个答案:

答案 0 :(得分:6)

原因是Tastypie在到达pre_save接收者之前失败了。根据你粘贴的追溯,它在full_hydrate失败了。这样做的原因是默认情况下main_gallery是必需的而且没有给出(因为您假设它将被创建)。

尝试将blank=True, null=True添加到

main_gallery = fields.OneToOneField(AlbumResource, 'main_gallery', related_name='project', full=False)