Django:检查列中是否存在该行

时间:2014-01-03 16:54:00

标签: python django

我想检查我的Django模板中user_id表中是否存在profile_images

我的模特

class profiles(models.Model):
    profile_id = models.AutoField(primary_key=True)
    user = models.ForeignKey(User)
    -----

class Profile_images(models.Model):
    id = models.AutoField(primary_key=True)
    user = models.ForeignKey(User)
    image = models.ImageField(upload_to='uploads/',default = 'uploads/no-img.jpg')

我的观点

def view_profiles(request):
    if request.user.is_authenticated():
        view_all_profiles = profiles.objects.all()
        profile_image = Profile_images.objects.all()
        return render_to_response('profiles/all.html', {'profiles':view_all_profiles,'profile_image':profile_image}, context_instance=RequestContext(request),)
    else:
        return HttpResponseRedirect('/accounts/login/')

我的模板

{% for profile in profiles %}
    <li>
        {% for image in profile_image %}
            {% ifequal image.user_id profile.user_id %}                         
                <img src="{{MEDIA_URL}}{{image.image}}" alt="image" />
            {% endifequal %}
            <!-- i want to check here if not user_id exist in profile_images table  -->
            {% if profile.user_id not in profile_image %}
                <img src="{% static 'images/no-image.jpg' %}" alt="image" />
            {% endif %}
        {% endfor %}
    </li>
{% endfor %}

{% if profile.user_id not in profile_image %}无效。我是Django&amp;的新手。蟒蛇,我被困在这里。如果我的代码不正确,请建议更好的方法。

2 个答案:

答案 0 :(得分:1)

在您的视图中,您可以使用个人资料图片获取所有user_id,例如:

user_ids_with_profile_images = Profile_images.objects.all().values_list('user_id', flat=True)

然后在您的模板中,您可以检查profile.user_id not in user_ids_with_profile_images


使用系统中的配置文件遍历所有用户并通过外键获取他们的个人资料图片,而不是遍历所有配置文件并尝试获取用户,实际上可能会更清洁一些......

答案 1 :(得分:1)

这实际上是一个设计问题,你可以专门为配置文件图像设置一个单独的模型,因为它可能只是配置文件模型本身的一个字段。

class Profile(models.Model): # convention is to use a non-plural name for models
    # No need to explicitly set the primary key, this will be added automatically
    # profile_id = models.AutoField(primary_key=True) 
    user = models.ForeignKey(User)
    image = models.ImageField(upload_to='uploads/',default = 'uploads/no-img.jpg')
    -----

现在只需要使用{{ profile.image }}而不需要任何额外的查找。