使用django tastypie创建两个相关的实例?

时间:2014-01-12 08:52:12

标签: django tastypie

我有以下模特关系。

class Thread:
  main_post = models.OneToOneField('Post', null=True, blank=True, related_name='+') 

class Post:
  thread = models.ForeignKey('Thread', related_name='posts')    

一个帖子有很多帖子,但是有一个名为 main_post 的特殊帖子,一个帖子有一个特殊的指针。

现在我想使用tastypie创建Post / Thread,这很难,因为tastypie使用https://stackoverflow.com/a/19948109/433570

中建议的related_name神奇地解决了问题

如何创建帖子/帖子?
我收到错误,因为帖子没有线程数据。

  /home/eugenekim/virtualenvs/zibann/local/lib/python2.7/site-packages/tastypie/resources.py(2083)obj_create()
-> bundle = self.full_hydrate(bundle)
  /home/eugenekim/virtualenvs/zibann/local/lib/python2.7/site-packages/tastypie/resources.py(876)full_hydrate()
-> value = field_object.hydrate(bundle)
  /home/eugenekim/virtualenvs/zibann/local/lib/python2.7/site-packages/tastypie/fields.py(740)hydrate()
-> return self.build_related_resource(value, request=bundle.request)
  /home/eugenekim/virtualenvs/zibann/local/lib/python2.7/site-packages/tastypie/fields.py(664)build_related_resource()
-> return self.resource_from_data(self.fk_resource, value, **kwargs)
  /home/eugenekim/virtualenvs/zibann/local/lib/python2.7/site-packages/tastypie/fields.py(624)resource_from_data()
-> fk_bundle = fk_resource.full_hydrate(fk_bundle)
  /home/eugenekim/virtualenvs/zibann/local/lib/python2.7/site-packages/tastypie/resources.py(876)full_hydrate()
-> value = field_object.hydrate(bundle)
  /home/eugenekim/virtualenvs/zibann/local/lib/python2.7/site-packages/tastypie/fields.py(735)hydrate()
-> value = super(ToOneField, self).hydrate(bundle)
  /home/eugenekim/virtualenvs/zibann/local/lib/python2.7/site-packages/tastypie/fields.py(166)hydrate()
-> elif self.attribute and getattr(bundle.obj, self.attribute, None):
> /home/eugenekim/virtualenvs/zibann/local/lib/python2.7/site-packages/django/db/models/fields/related.py(324)__get__()
-> "%s has no %s." % (self.field.model.__name__, self.field.name))

修改

现在我只设置related_name ='thread',它似乎正在工作。

class PostResource(ApiResourceMixin, VoteMixin, DeleteUndeleteMixin, NamespacedModelResource):

    thread = fields.ForeignKey('momsplanner.api.resources.forum.ThreadResource', attribute='thread', null=True, blank=True)
    parent_post = fields.ForeignKey('momsplanner.api.resources.forum.PostResource', attribute='parent_post', null=True)
    user = fields.ForeignKey('site_common.api.resources.user.UserResource', attribute='user', full=True, readonly=True)
    created_at = fields.DateTimeField(attribute='created_at', readonly=True)


class ThreadResource(ApiResourceMixin, SearchMixin, NamespacedModelResource):
    '''used when you need thread of multiple types and their respective fields'''
    from momsplanner.models import forum as c_forum_models
    main_post = fields.ForeignKey('momsplanner.api.resources.forum.PostResource', 'main_post', full=True, related_name='thread')

0 个答案:

没有答案