0

I found this code for a blog post app written using Django here: I am confused with what this snippet of code does: Please explain what the CommentManager class below do and how the parameters passed to it are assigned to some 'arbitrary keys'. The same object is used in Comment class below. How is that used?

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'),
    )
eagertoLearn
  • 9,772
  • 23
  • 80
  • 122

1 Answers1

0

by default every Model in Django has a manager. The default one is a very simple - for example, when you write Comment.objects.all(), it's equivalent to a "SELECT * FROM ". You can also filter, for ex: Comment.objects.filter(is_public=True) You can however write your own managers (CommentManager in this example) for custom queries. Here the CommentManager is assigned to Comment: objects=CommentManager() which allows you to do request like this:

Comment.objects.comments_for_object(params)

Where params are (site_id, app_label, model, obj_id, comment_type). The code simply maps those params into the query.

Note that you can change the name by which you will access your Managers. You could write:

obj_comments=CommentManager()

then call:

Comment.obj_comments.comments_for_object(params)
Pawel Kozela
  • 484
  • 5
  • 12