Получить данные из родительской модели, используя внешний ключ
Как пользователь может получить доступ ко всем данным клиента (модель клиента), когда пользователь проверяет данные счета (из модели счета), который имеет внешний ключ
модель клиента
class Clients(models.Model):
company_name = models.CharField(max_length=200, blank=True, null=True)
clients_name = models.CharField(max_length=200, blank=True, null=True,)
phone_number = models.IntegerField(blank=True, null=True )
email = models.EmailField(blank=True, null=True )
модель счета
class Invoice(models.Model):
clients_name = models.ForeignKey(Clients, on_delete=models.CASCADE, blank=True, null=True)
invoice_number = models.CharField(max_length=200, blank=True, null=True)
slug = models.SlugField(unique =True)
due_date = models.DateField()
cost = models.CharField(max_length=200, blank=True, null=True)
Вот здесь я застрял
У меня есть представление для получения подробностей о счете-фактуре. Но теперь я хочу, чтобы пользователь также мог просматривать все детали клиента из модели клиента на основе имени_клиента (внешний ключ)
def single_invoice_details(request, slug):
try:
invoice_details = Invoice.objects.get(slug=invoice_number)
except:
return HttpResponse('cannot be found')
return render(request, 'invoices/invoice_details.html', {'invoice_details': invoice_details})
Что я пробовал
def single_invoice_details(request, slug):
try:
invoice_details = Invoice.objects.get(slug=invoice_number)
except:
return HttpResponse('cannot be found')
clients_details = Clients.objects.filter(clients_name=invoice_details)
return render(request, 'invoices/invoice_details.html', {'invoice_details': invoice_details,'clients_details':clients_details})
Выяснилось, что для получения данных о клиенте не нужно ничего добавлять в представление. Добавьте invoice_details.client_name.phone_number
или invoice_details.client_name.email
в шаблон Django