Как я могу включить обратно связанные элементы в сериализатор Django?
Я пытаюсь добавить все Payments, которые относятся к PayrollRun в сериализаторе, чтобы они также возвращали это. Но как я могу добавить обратные отношения к сериализатору?
# views.py
class PayrollRun(APIView):
"""
Retrieve payroll runs including line items for a company
"""
def get(self, request):
# Get the related company according to the logged in user
company = Company.objects.get(userprofile__user=request.user)
payroll_runs = Payroll.objects.filter(company=company)
serializer = PayrollSerializer(payroll_runs, many=True)
return Response(serializer.data)
# models.py
class Payroll(models.Model):
"""
A table to store monthly payroll run information of companies
"""
# Relates to one company
company = models.ForeignKey(Company, on_delete=models.CASCADE)
month = models.DateField()
amount = models.DecimalField(decimal_places=2, max_digits=10)
line_items = models.PositiveIntegerField()
def __str__(self):
return f'Payroll run month {self.month} for company {self.company.name}'
class Payment(models.Model):
"""
A table to store all payments derived from an offer
"""
# Relations
offer = models.ForeignKey(Offer, on_delete=models.CASCADE)
month = models.ForeignKey(Period, on_delete=models.CASCADE)
payroll_run = models.ForeignKey(Payroll, on_delete=models.CASCADE, null=True, blank=True) # is populated once the payroll run was created
amount = models.DecimalField(decimal_places=2, max_digits=10)
def __str__(self):
return f'{self.offer} with an amount of {self.amount} and payment month {self.month}'
# serializers.py
class PayrollSerializer(serializers.ModelSerializer):
class Meta:
model = Payroll
depth = 1
fields = '__all__'
прямо сейчас возвращает следующее без соответствующих экземпляров платежей
[
{
"id": 12,
"month": "2022-04-01",
"amount": "7570.02",
"line_items": 2,
"company": {
"id": 1,
"name": "Example Ltd.",
"country": "Germany",
"city": "Munich",
"zip": "80801",
"street": "Max-Strasse",
"house_number": "3",
"vat": "DE12434",
"customer_number": "1",
"fee_offer": "59.00",
"is_active": true
}
},
{
"id": 13,
"month": "2022-06-01",
"amount": "733.00",
"line_items": 1,
"company": {
"id": 1,
"name": "Example Ltd.",
"country": "Germany",
"city": "Munich",
"zip": "80801",
"street": "Max-Strasse",
"house_number": "3",
"vat": "DE12434",
"customer_number": "1",
"fee_offer": "59.00",
"is_active": true
}
}
]