如何从Django数据库模型获取数据?我的实现遇阻求助
问题排查与解决方法
核心错误点
- 错误1:
values()返回字典而非模型实例Post.objects.all().values()返回的是字段键值对组成的字典列表,不是Post模型实例。你的循环里判断"如果是字典就跳过",等于直接放弃了所有数据,最终post_contents是空的。 - 错误2:未关联当前候选人的博客
你取了所有Post数据,但需求是获取当前简历对应的博客内容,应该通过Resume与Post的外键关联来筛选。 - 错误3:冗余字段
blog_post
Resume模型里的blog_post字段完全多余,因为Post已经通过resume外键和Resume建立关联,直接通过关联关系就能获取博客内容。
正确实现代码
优化后的views.py
from django.views.generic import View from .models import Resume, Post from django.shortcuts import render class CandidateView(View): def get(self, request, **kwargs): pk = kwargs['pk'] candidate = Resume.objects.get(pk=pk) # 通过Resume的反向关联直接获取对应所有Post实例 posts = candidate.posts.all() # 若仅需内容列表,可改用列表推导式: # post_contents = [post.content for post in posts] return render(request, 'blog/candidate.html', {'candidate': candidate, 'posts': posts})
清理后的models.py(移除冗余字段)
from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Resume(models.Model): name = models.CharField(max_length=100) dob = models.DateField(auto_now=False, auto_now_add=False) gender = models.CharField(max_length=100) locality = models.CharField(max_length=100) city = models.CharField(max_length=100) pin = models.PositiveIntegerField() state = models.CharField(choices=STATE_CHOICE, max_length=50) mobile = models.PositiveIntegerField() email = models.EmailField() job_city = models.CharField(max_length=50) profile_image = models.ImageField(upload_to='profileimg', blank=True) my_file = models.FileField(upload_to='doc', blank=True) # 移除冗余的blog_post字段 class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) resume = models.ForeignKey(Resume, on_delete=models.CASCADE, related_name='posts', null=True, blank=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk})
模板页面(candidate.html)展示示例
<h1>{{ candidate.name }}的简历</h1> <!-- 其他简历信息展示 --> <h2>我的博客</h2> {% for post in posts %} <div class="post"> <h3>{{ post.title }}</h3> <p>{{ post.content }}</p> <small>发布于: {{ post.date_posted|date:"Y-m-d" }}</small> </div> {% empty %} <p>暂无博客内容</p> {% endfor %}
额外说明
- 利用Django反向关联:因为Post模型给Resume外键设置了
related_name='posts',所以直接通过candidate.posts.all()就能获取该候选人的所有博客,无需手动筛选。 - 避免滥用
values():除非只需要特定字段的字典数据,否则直接获取模型实例更便于后续操作和模板渲染。 - 若仅需博客内容列表,用列表推导式
[post.content for post in candidate.posts.all()]即可,无需循环判断类型。
内容的提问来源于stack exchange,提问作者Merina Tanjin
相关产品推荐
相关产品推荐

