Django根据GET请求从数据库中过滤数据

2024-09-28 23:16:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习django,希望根据用户的请求查询数据。这是我的代码:

在模型.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)

在网址.py公司名称:

^{pr2}$

在视图.py以下内容:

def airlinedata(request):
    data = FinancialData.objects.filter(pk=airline_id)
    return data

我不确定我应该在views.py中写什么,例如当用户选择3的airline\uid时,它只使用外键从该航空公司的数据库中检索FinancialData?在


Tags: 用户pytruemodelmodelsmaxclassdecimal
3条回答

如果航空公司是金融数据的外键,那么航空公司与金融数据之间存在一对多的关系。它意味着:

  obj = Airline.objects.get(pk=3)

只会给你一个对象。这个对象有许多附加的财务数据,你可以通过说:

^{pr2}$

一旦你有了以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()

我希望这有帮助!在

首先将pk作为参数添加到函数中

def airlinedata(request, pk):

然后获取与pk关联的Airline对象

^{pr2}$

然后过滤所有与该航空公司相关的财务数据

data = FinancialData.objects.filter (airline=airline)

抱歉格式化,使用电话。在

你的观点应该是这样的:

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参数与^{}的正则表达式中的参数相同
  • 对查询集调用^{}
  • 返回^{}而不是平面字符串

相关问题 更多 >