我正在学习django,并希望根据用户的请求查询数据。这是我的代码:
models.py:
class Airline(models.Model):
name = models.CharField(max_length=10, blank=True, null=True)
code = models.CharField(max_length=2, blank=True, null=True)
class FinancialData(models.Model):
airline = models.ForeignKey(Airline)
mainline_revenue = models.DecimalField(max_digits=7, decimal_places=2)
regional_revenue = models.DecimalField(max_digits=7, decimal_places=2)
other_revenue = models.DecimalField(max_digits=7, decimal_places=2)
total_revenue = models.DecimalField(max_digits=7, decimal_places=2)
urls.py:
urlpatterns = [
url(r'^airline/(?P<pk>\d+)/$', views.airlinesdata, name='airline_data'),
]
views.py:
def airlinedata(request):
data = FinancialData.objects.filter(pk=airline_id)
return data
我不确定在views.py
中应该写什么,当用户选择例如 airline_id 为3时,它会从数据库中检索 FinancialData 航空公司只使用外键?
答案 0 :(得分:3)
如果航空公司是FinancialData的ForeignKey,那么航空公司与FinancialData之间存在一对多的关系。这意味着:
obj = Airline.objects.get(pk=3)
会给你一个对象。这个对象附加了许多FinancialData,您可以通过以下方式检索:
financial_data = obj.financial_data_set.all() //Django has _set for all ForeignKey relationship.
一旦你的观点以pk为参数,你可以从财务数据中查询航空公司,反之亦然:
def airlinedata(request, pk):
financial = FinancialData.objects.filter(airline__pk=pk)
# Notice the double underscore, it's called field lookup. You can lookup fields in other model from a model using it.
# If u get your airline data first however by using:
airline = Airline.objects.get(pk=pk)
# You can obtain all financial data attached to it thus:
financials = airline.fiancial_data_set.all()
我希望有所帮助!
答案 1 :(得分:1)
您的观点应如下所示:
def airlinedata(request, pk):
airline = Airline.objects.filter(pk=pk).first()
fiancial_data = airline.fiancial_data_set.all()
all_ids = [fin.id for fin in fiancial_data] # Or any other info you need
return HttpResponse(str(all_ids))
变化是:
pk
参数与urls.py
正则表达式相同first()
HttpResponse
而非平面字符串答案 2 :(得分:1)
首先将pk作为参数添加到您的函数中;
def airlinedata(request, pk):
然后获取与该pk相关联的航空公司对象;
airline = Airline.objects.get (id=pk)
然后过滤与该航空公司关联的所有FinancialData;
data = FinancialData.objects.filter (airline=airline)
抱歉使用手机进行格式化。