在Django模板中过滤多对一

时间:2018-03-30 21:58:56

标签: python django orm

我们说我有这些模型:

from itertools import groupby

lst = [[2, 1], [5, 1], [10, 1], [9, 1], [10, 2], [18, 2]]

for _, grp in groupby(lst, key=lambda x:x[1]):
    grp = list(grp)
    print (sum((i<j) for i,j in zip(grp, grp[1:])))

和以下观点:

class Profile(models.Model):
    headline     = models.CharField(max_length=200)

class ProfilePhoto(models.Model):
    photo        = models.ImageField(upload_to='profiles/photos')
    owner        = models.ForeignKey(Profile, related_name='photos', on_delete=models.CASCADE)
    type_choices = (
        ('PR', 'Primary'),
        ('AD', 'Additional'),
    )
    type         = models.CharField(max_length=2, choices=type_choices, default='AD')  

这在我的模板文件中:

def profiles(request):
    # Retrieve all active profiles
    profiles = Profile.objects.filter(status='AC').order_by('-updated_at')#.filter(photos__)
    context = {'profiles': profiles}

    return render(request, 'profiles.html', context)   

由于模板中的{% for profile in profiles %} <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12"> <div class="panel panel-default"> <div class="panel-body"> <p><a href="{{ profile.get_absolute_url }}">{{ profile.headline }}</a></p> <img src="{{ MEDIA_URL }}profiles/thumbs/{{ profile.photos.first.photo }}"> </div> </div> </div> {% endfor %} ,我为每个配置文件获取了一张照片,但我想要的是为每个配置文件选择一张照片,条件是它的类型为&#39; PR&# 39 ;.任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

您可以使用model method。像这样:

class Profile(models.Model):
    headline = models.CharField(max_length=200)

    @property
    def primary_profile_photo(self):
        primary_photo = self.photos.filter(type='PR').order_by('?').first()
        return primary_photo.photo

这会为您提供一张类型为order_by='?'的随机(PR)照片,然后您可以在模板中以primary_profile_photo进行访问。