我想从两个表Project和User1中获取并显示详细信息(name_project,user_name)
models.py
class Project(models.Model):
name_project = models.CharField(max_length=50)
leader = models.ForeignKey('User1', default='')
category_project = models.CharField(max_length=50)
class User1(models.Model):
user_name = models.CharField(max_length=30)
mail = models.EmailField(max_length=50)
password = models.CharField(max_length=50)
views.py
def list_project(request):
queryset = Project.objects.raw(
'SELECT scrum_rest_project.id, scrum_rest_project.name_project, scrum_rest_user1.user_name FROM scrum_rest_user1,scrum_rest_project WHERE scrum_rest_user1.id = scrum_rest_project.leader_id')
queryset = serializers.serialize('json', queryset)
return HttpResponse(queryset, content_type="application/json")
但它只显示json文件中Project表中的数据,我想显示来自User1表的数据
答案 0 :(得分:1)
您应该使用select related feature:
Project.objects.select_related().all()
答案 1 :(得分:1)
为什么使用原始SQL?了解Querysets。
的 1。使用Querysets:
projects = Project.objects.select_related('leader').all()
for project in projects:
print project.name, project.leader.user_name
注意:
select_related
创建与User1
的联接,并在访问User1
模型时为您节省额外的SQL查询
<强> 2。只获取领导者和项目名称列表。
project_list = Project.objects.select_related('leader')\
.values_list('name', 'leader__user_name')