通过与Tastypie的反向关系访问对象的注释

时间:2014-06-27 14:00:36

标签: python django tastypie django-comments

我正在使用Tastypie和Django构建API,我遇到了一些问题。

我有一个名为Moment的模型(基本上是博客文章,标题和正文),我希望能够附加评论并通过API检索它们。我正在使用django.contrib.comments与Django 1.6.5和Tastypie 0.11.1。

现在,根据Tastypie文档,this should be straightforward。我实施的内容非常接近。这是我的models.py

class Moment(models.Model):
    """ 
    Represents a Moment - a statement by a user on a subject
    """
    ZONE_CHOICES = ( 
                   ('Communication', 'Communication'),
                   ('Direction', 'Direction'),
                   ('Empathy', 'Empathy'),
                   ('Flexibility', 'Flexibility'),
                   ('Motivation', 'Motivation'),
                   ('Ownership', 'Ownership'),
                   ('Persistence', 'Persistence'),
                   ('Reliability', 'Reliability'),
                   ('Teamwork', 'Teamwork'),
    )   
    STATUS_CHOICES = ( 
                     ('Open', 'Open'),
                     ('More Info', 'More Info'),
                     ('Closed', 'Closed'),
    )   
    title = models.CharField(max_length=200)
    text = models.TextField()
    datetime = models.DateTimeField(default=timezone.now())
    zone = models.CharField(max_length=200,
                            choices=ZONE_CHOICES)
    sender = models.ForeignKey(Student, blank=True, null=True, related_name="sender")
    status = models.CharField(max_length=200,
                              default='Open',
                              choices=STATUS_CHOICES)
    recipient = models.ForeignKey(Sponsor, blank=True, null=True, related_name="recipient")
    comments = generic.GenericRelation(Comment, object_id_field='object_pk')

    def save(self, *args, **kwargs):
        """
        Override the save() method to set the recipient dynamically
        """
        if not self.recipient:
            self.recipient = self.sender.sponsor
        super(Moment, self).save(*args, **kwargs)


    def __unicode__(self):
        return self.title

    class Meta:
        ordering = ["-datetime"]

这是我的api.py

class MomentResource(BaseResource):
    """ 
    Moment resource
    """
    sender = fields.ForeignKey(StudentResource, 'sender', full=True, readonly=True)
    comments = fields.ToManyField('myapp.api.CommentResource', 'comments', blank=True, null=True)

    class Meta:
        """
        Metadata for class
        """
        queryset = Moment.objects.all()
        resource_name = 'moment'
        always_return_data = True
        authentication = BasicAuthentication()
        authorization = DjangoAuthorization()
        filtering = { 
            'zone': ALL,
        }


class CommentResource(ModelResource):
    """ 
    Comment resource
    """
    moment = fields.ToOneField(MomentResource, 'moment')

    class Meta:
        queryset = Comment.objects.all()
        resource_name = 'comments'

但是,评论总是空白。

现在,我知道该模型似乎是正确的,因为在Django shell中,以下内容返回片刻的注释:

Moment.objects.all()[0].comments.all()

我认为问题出在api.py,但我无法追踪它。谁能看到我误入歧途的地方?

1 个答案:

答案 0 :(得分:0)

最后让它使用以下内容:

class MomentResource(BaseResource):
    """ 
    Moment resource
    """
    sender = fields.ForeignKey(StudentResource, 'sender', full=True, readonly=True)
    comments = fields.ToManyField('myapp.api.CommentResource', 'comments', null=True, full=True)

    class Meta:
        """
        Metadata for class
        """
        queryset = Moment.objects.all()
        resource_name = 'moment'
        always_return_data = True
        authentication = BasicAuthentication()
        authorization = DjangoAuthorization()
        filtering = { 
            'zone': ALL,
        }


class CommentResource(BaseResource):
    """ 
    Comment resource
    """
    moment = fields.ToOneField(MomentResource, 'content_object')

    class Meta:
        queryset = Comment.objects.all()
        resource_name = 'comments'

我很确定问题是从Moment返回CommentResource对象,通过将属性更改为content_object来解决此问题。