如何使用foreignKey?
请使用foreignKey帮助检索和显示数据
class Gender(models.Model):
gender = models.CharField(
max_length=10,
blank=False,
)
class UserProfile(User):
name1 = models.CharField(
'Имя',
max_length=30,
blank=True,
null=True,
)
gender = models.ForeignKey(
Gender,
default=0,
)
灯具:
[
{
"model": "drummersaransk.Gender",
"pk": 1,
"fields": {
"gender": "none"
}
},
{
"model": "drummersaransk.Gender",
"pk": 2,
"fields": {
"gender": "male"
}
},
{
"model": "drummersaransk.Gender",
"pk": 3,
"fields": {
"gender": "female"
}
}
]
views.py:
def user_personal(request, id):
entries_user_profile = UserProfile.objects.get(user_ptr_id=id)
t = loader.get_template('user_personal.html')
c = RequestContext(request, {
'entries_user_profile': entries_user_profile,
})
return HttpResponse(t.render(c))
user_personal.html:
{% if entries_user_profile.gender_id %}
<tr>
<td class="label">Пол</td>
<td class="gender info">{{ entries_user_profile.gender_id }}</td>
</tr>
{% endif %}
问题在于性别不是表性别(无,男性或女性)的输出值
答案 0 :(得分:1)
你出gender.id
,而不是性别名称。
尝试替换此
<td class="gender info">{{ entries_user_profile.gender_id }}</td>
用这个
<td class="gender info">{{ entries_user_profile.gender.gender }}</td>
<强>更新强>
也许choices
是存储用户性别的更好方法。看看:https://docs.djangoproject.com/en/dev/ref/models/fields/#choices