使用Django检索已过滤的ForeignKey

时间:2017-12-10 22:27:40

标签: python django tags django-queryset prefetch

我有三个主要模型,Picture,Place和PlaceRating:

class Picture(models.Model):
    file = ImageField(max_length=500, upload_to="images")
    user = models.ForeignKey(User, null=True, related_name="userpictures")
    place = models.ForeignKey(Place, null=True, related_name='pictures')

class PlaceRating(models.Model):
    place = models.ForeignKey(Place, null=True, related_name="placeratings")
    user = models.ForeignKey(User, null=True, related_name="userratings")   
    rating = models.DecimalField(null=True, max_digits=4, decimal_places=1)     

class Place(models.Model):
    name = CharField(max_length=50)

我想显示用户提供的地点评级以及地点的图片,但我无法设法做到这一点,因为我需要过滤ForeignKey而Django似乎没有允许这样做。

我想做的例子:

查看:

pictures = Picture.objects.filter(user=request.user)

模板:

{% for picture in pictures %}
    <img src="{{ picture.file.url }}" class="bigpicture">
    {{ picture.place.placeratings.0.rating|user:picture.user }}
{% endfor %}

有关信息,我设法使用templatetags,但这会为数据库生成许多不同的查询,我无法预取..:

{% for picture in pictures %}
    <img src="{{ picture.file.url }}">
    {% getplaceratingrelatedtopic picture.place.id picture.user.id %}
{% endfor %}

@register.simple_tag
def getplaceratingrelatedtopic(placeid, userid):
    print(placeid)
    theplace = Place.objects.get(id=placeid)
    user = User.objects.get(id=userid)
    placerating = PlaceRating.objects.filter(author=user, place=place).last()
    if rating:
        return placerating.rating
    else:
        return ""

我使用Python 2.7 / Django 1.9。

有任何线索吗?非常感谢!

1 个答案:

答案 0 :(得分:0)

您应该将逻辑移动到模型并在模板中使用它。

class Picture(models.Model):
    file = ImageField(max_length=500, upload_to="images")
    user = models.ForeignKey(User, null=True, related_name="userpictures")
    place = models.ForeignKey(Place, null=True, related_name='pictures')


class PlaceRating(models.Model):
    place = models.ForeignKey(Place, null=True, related_name="placeratings")
    user = models.ForeignKey(User, null=True, related_name="userratings")   
    rating = models.DecimalField(null=True, max_digits=4, decimal_places=1)     


class Place(models.Model):
    name = CharField(max_length=50)

    @property
    def rating(self):
        return self.placeratings.get().rating

{% for picture in picture_list %}
    <img src="{{ picture.file.url }}" class="bigpicture">
    {{ picture.place.rating }}: {{ picture.user.username }}
{% endfor %}