【问题标题】:Accessing comments on an object via reverse relationship with Tastypie通过与 Tastypie 的反向关系访问对象的评论
【发布时间】:2014-06-27 14:00:36
【问题描述】:

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

我有一个名为 Moment 的模型(基本上是一篇博客文章,带有标题和正文),我希望能够将 cmets 附加到它并通过 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'

但是,cmets 总是返回空白。

现在,我知道模型似乎是正确的,因为在 Django shell 中,以下内容会在某个时刻返回 cmets:

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

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

【问题讨论】:

    标签: python django tastypie django-comments


    【解决方案1】:

    终于可以使用以下方法了:

    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'
    

    我很确定问题在于从 CommentResource 返回 Moment 对象,通过将属性更改为 content_object 解决了这个问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-05
      • 1970-01-01
      • 2023-03-09
      相关资源
      最近更新 更多