我有一个django应用程序,必须显示国家名称和城市名称" need"在候选人名单中。 为了更好地解释这一点,我有下一张图片:
所以,这是一个过程: 首先,有人发布了" need"与各自的国家和城市。 城市和国家是不同的模式。
然后,候选人可以提出解决该需求的提议。
我想在列表中看到我发送给需求的所有优惠(仅需1个优惠),但在我的html模板中,我想显示国家名称和需要的城市。
这是我的 models.py
class requiter (models.Model):
requiter_name = models.CharField(max_length=200, null=True)
class country (models.Model):
country_name = models.CharField(max_length=200, null=True)
class city (models.Model):
city_name = models.CharField(max_length=200, null=True)
class candidate (models.Model):
full_name=models.CharField(max_length=230, null=True)
class need(models.Model):
requiter = models.ForeignKey(requiter, on_delete=models.CASCADE, null=True)
title= models.CharField(max_length=300, null=True)
description=models.TextField(null=True)
country=models.ForeignKey(country, on_delete=models.CASCADE, null=True)
city=models.ForeignKey(city, on_delete=models.CASCADE, null=True)
class offer(models.Model):
need = models.ForeignKey(need, on_delete=models.CASCADE, null=True)
candidate = models.ForeignKey(candidate, on_delete=models.CASCADE, null=True)
这是我的 views.py
def candidateprofile(request):
candata = candidate.objects.get(id=request.session['account_id'])
#HERE IS WHERE I WANT TO TAKE ALL THE OFFERS THAT THE CANDIDATE MADE, AND THE NAME OF THE COUNTRY AND CITY IN THE NEEDS
myoffers = offer.objects.filter(candidate_id = request.session['account_id'] )
#??????
dic.update({'candata': candata, 'jobapplies': jobapplies})
return render(request, 'my_app/candidateProfile.html', dic)
在SQL中,等价物是下一个:
SELECT o.need_id, n.title, r.recruiter_name, c.country_name, y.city_name FROM offer AS o
INNER JOIN need AS n ON o.need_id = n.id
INNER JOIN requiter AS r ON n.recruiter_id = r.id
INNER JOIN country AS c ON n.country_id = c.id
INNER JOIN city AS y ON n.city_id = y.id
WHERE o.candidate_id = sended_parameter
但我不知道如何在django中做到这一点。请帮助!
答案 0 :(得分:1)
你不应该用这些术语思考。你应该考虑如何获得你想要的对象。在您的情况下,您需要引用候选商品的Need对象。所以:
needs = Need.objects.filter(offer__candidate=request.session['candidate_id'])
现在您可以迭代需求并获得need.country.country_name
和need.city.city_name
;这将是低效的,因为它会导致对每次访问的查询,因此我们可以向查询添加select_related
:
needs = needs.select_related('country', 'city')