0

我试图弄清楚如何在模板中显示下面扩展用户模型中的 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 显示评级。

4

1 回答 1

1

您可以这样做:向 中添加一个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 %}
于 2013-10-29T20:42:22.080 回答