如何从Django中的扩展用户访问字段?

时间:2013-10-29 20:30:53

标签: python django django-models django-templates django-views

我试图弄清楚如何在模板中显示下面的扩展用户模型中的userRating字段,但没有显示任何内容。

型号:

class userProfile(models.Model):
    user = models.OneToOneField(User)
    USER_RATING_CHOICES = (("1 star", "1 Star(s)"), ("2 star", "2 Star(s)"), ("3 star", "3 Star(s)"), ("4 star", "4 Star(s)"), ("5 star", "5 Star(s)"))        
    userRating = models.CharField("User rating", max_length=6, choices=USER_RATING_CHOICES, default="1 star")

class partListing(models.Model):
    partName = models.CharField("Name", max_length=200)
    datePublished = models.DateTimeField("Date published")
    postedBy = models.ForeignKey(User)
    def __unicode__(self):
        return self.partName

查看:

def browse(request):
    partListingTitle = partListing.objects.filter(partName__startswith='2010')
    # Note: the startswith query here is just for testing
    return render_to_response("partmanager/browse.html",
                             {'partListingTitle' : partListingTitle},
                             context_instance=RequestContext(request))

我要做的是在我的模板中使用User rating: 3 stars之类的东西。我设法让postedBy字段工作,但我无法让userRating显示评级。

1 个答案:

答案 0 :(得分:0)

您可以这样做:向related_name添加OneToOneField属性,然后使用.访问者对其进行反向访问。

class userProfile(models.Model):
    user = models.OneToOneField(User, related_name='profile')
    USER_RATING_CHOICES = (("1 star", "1 Star(s)"), ("2 star", "2 Star(s)"), ("3 star", "3 Star(s)"), ("4 star", "4 Star(s)"), ("5 star", "5 Star(s)"))        
    userRating = models.CharField("User rating", max_length=6, choices=USER_RATING_CHOICES, default="1 star")

然后,

{% for listing in partListingTitle %}
    {{listing.postedBy.profile.userRating}}
{% endfor %}