开发者

display # of comments for a UserProfile in Django

How do I connect my UserProfile model to a User's Comments? In my UserProfileAdmin I would like to show # of comments for each User. Any ideas?

Thanks!

EDIT: My Model:

class UserProfile(models.Model):
    GENDER_CHOICES = (
                      ('M', _('Male')),
                      ('F', _('Female')))
    user = models.ForeignKey(User, unique=True)
    location = models.CharField(max_length=50)
    gender = models.CharField(max_length=2, choices=GENDER_CHOICES, blank=True, null=True)
    birthdate = models.DateField(blank=True, null=True)
    website = models.URLField(blank=True)
    description = models.TextField(bla开发者_C百科nk=True)

I also would like to display the User's list of comments when viewing a UserProfile. Since I am using Django's built-in comment system, is there a shortcut to do this? Or do I have to do something like Comments.objects.filter(user=user) something like that?


UserProfile.user.comment_comments.count()

should do it.

You could wrap this into a method on your profile model

def count_comments(self):
    if self.user:
        return self.user.comment_comments.count()

and add count_comments to the list_display option in your ModelAdmin.


If you want to get the list of a user's comments you could tweak the method accordingly:

def get_comments(self):
    if self.user:
        return self.user.comment_comments.all()

Then you can do:

User.objects.get(pk=1).comment_comments.all()

or:

UserProfile.objects.get(pk=1).get_comments()


While registering admin (or if you creating custom one) just use field something like UserComments.filter(user).count() Its hard to tell not knowing how your models look like. but the main idea is to direct that field to that specific user comments and use .count(). I could update my answer (or others would answer better) if you would provide more code.

UPDATE: sorry forgot the docs. For .count(): http://docs.djangoproject.com/en/dev/ref/models/querysets/#count
for filters: http://docs.djangoproject.com/en/dev/ref/models/querysets/#filter
for registering admin: http://docs.djangoproject.com/en/dev/ref/contrib/admin/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜