0

我找到了使用此处编写的博客文章应用程序Django的代码:我对这段代码的作用感到困惑:请解释下面的 CommentManager 类的作用以及传递给它的参数如何分配给某些“任意键”。object在下面的课程中也使用相同的方法Comment。那是怎么用的?

class CommentManager(models.Manager):
    def comments_for_object(self, site_id, app_label, model, obj_id, comment_type='comment'):
        ''' Get a QuerySet of all public comments for the specified object. '''
        kwargs = {
            'site__id__exact': site_id,
            'content_type__app_label__exact': app_label,
            'content_type__model__exact': model,
            'object_id__exact': obj_id,
            'comment_type__exact': comment_type,
            'is_public__exact': True,
        }
        return self.filter(**kwargs)


class Comment(models.Model):
    ''' Data model for both comments and trackbacks '''
    objects = CommentManager()

    content_type = models.ForeignKey(ContentType)
    object_id = models.IntegerField(_('object ID'))
    comment = models.TextField(_('comment'), max_length=3000)
    submit_date = models.DateTimeField(_('date/time submitted'), auto_now_add=True)
    is_public = models.BooleanField(_('is public'))
    ip_address = models.IPAddressField(_('ip address'))

    site = models.ForeignKey(Site)

    typeChoices = (
        ('comment', 'Comment'),
        ('trackback', 'Trackback'),
    )
4

1 回答 1

0

默认情况下,Django 中的每个模型都有一个管理器。默认是一个非常简单的——例如,当你写 时Comment.objects.all(),它相当于一个“SELECT * FROM”。您还可以过滤,例如: Comment.objects.filter(is_public=True) 但是您可以为自定义查询编写自己的管理器(本示例中为 CommentManager)。这里的 CommentManager 被分配给 Comment: objects=CommentManager(),它允许你做这样的请求:

Comment.objects.comments_for_object(params)

参数在哪里(site_id、app_label、model、obj_id、comment_type)。该代码只是将这些参数映射到查询中。

请注意,您可以更改访问经理的名称。你可以写:

obj_comments=CommentManager()

然后调用:

Comment.obj_comments.comments_for_object(params)
于 2014-03-14T22:54:48.467 回答