Django模型在存在关联的地方获取数据

时间:2018-12-07 21:50:34

标签: django django-models

我有三个Django模型:

@python_2_unicode_compatible
class GroupInvoice(models.Model):
  group      = models.ForeignKey('Group', on_delete=models.CASCADE)
  invoice    = models.ForeignKey('Invoice', on_delete=models.CASCADE)
  created_at = models.DateField(auto_now_add=True)
  updated_at = models.DateField(auto_now=True)

  def __str__(self):
    return str(self.invoice.number) + ' ' + self.group.group_name


@python_2_unicode_compatible
class ProviderInvoice(models.Model):
  provider = models.ForeignKey('Provider', on_delete=models.CASCADE)
  invoice = models.ForeignKey('Invoice', on_delete=models.CASCADE)
  paid=models.BooleanField()
  created_at=models.DateField(auto_now_add=True)
  updated_at=models.DateField(auto_now=True)  
  def __str__(self):
    return self.invoice.invoice_number + ' ' +self.provider.first_name


@python_2_unicode_compatible
class Invoice(models.Model):
  number     = models.IntegerField(null=True, blank=True) #NOT THE INVOICE ID might be changed by user
  total      = models.DecimalField(max_digits=11,decimal_places=2) # 10 digit max, 
  date       = models.DateField(auto_now=False, auto_now_add=False)
  paid       = models.BooleanField(default=False)
  created_at = models.DateField(auto_now_add=True)
  updated_at = models.DateField(auto_now=True)

  def __str__(self):
    return 'PK: ' + str(self.pk) + ' InvoiceID: ' + str(self.number) + ' ' + str(self.total)

我仍然对模型中的关系有些模糊,但是我正在向视图发送所有发票的列表:

class InvoiceListView(TemplateView):
  template_name = 'ipaswdb/invoice/list.html'

  def get(self, request, *args, **kwargs):
    context = super(InvoiceListView, self).get_context_data(**kwargs)

    status_requested = None
    invoices = None

    if request.GET.has_key('status'):
      status_requested = request.GET['status']
      status_requested = status_requested.split('/')[0]  # drop any trailing / (forward slashes)


    if status_requested:
      invoices = Invoice.objects.all()
      invoice_status = 'all'
    else:
      invoices = Invoice.objects.all()
      invoice_status = 'all'

    context['num_invoices'] = len(invoices)
    context['invoices'] = invoices
    context['invoice_status'] = invoice_status



    return render(request,self.template_name,context)

事实证明,我真的很想获取组数据。正如在GroupInvoice中定义为group一样,我是否可以将这种关系放入模型中这样说:

invoices = Invoices.objects.all()
print(invoices[0].group.group_name)

我认为我需要在模型中使用更多语法才能使其工作?

1 个答案:

答案 0 :(得分:1)

尝试invoice.group_invoice_set,然后您便有了一个RelatedManager,可以在其中访问您的群组。 (请注意,它会产生一个新查询,因此请使用prefetch_related)

否则,进行内部连接,例如GroupInvoice.objects.select_related().filter(invoice_id=id)

了解更多:https://docs.djangoproject.com/en/2.1/ref/models/relations/