Reputation: 3816
I have three Django Models:
@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)
I am still a bit fuzzy on relationships in the models, but I WAS sending to a view a list of all invoices:
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)
It turns out I would really like to get the group data. As defined as group in GroupInvoice, is there anyway I can put that relationship into the model to say like :
invoices = Invoices.objects.all()
print(invoices[0].group.group_name)
I think I need some more syntax in the model to make this work like this?
Upvotes: 0
Views: 47
Reputation: 96
Try invoice.group_invoice_set
and then you have a RelatedManager where you can access to your groups. (Beware, it makes a new query, so use prefetch_related)
Otherwise make an inner join like GroupInvoice.objects.select_related().filter(invoice_id=id)
.
Read more: https://docs.djangoproject.com/en/2.1/ref/models/relations/
Upvotes: 1