I am having a Person
model to store person details.
class Person(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
birthdate = models.DateField()
also i am having model PersonLogs
to store person's activity logs.
class PersonLogs(models.Model):
person = models.ForeignKey(Person)
time = models.DateTimeField(auto_now_add=True)
I am using Django Serializer to return Person objects into JSON format as response.
from django.core import serializers
data = serializers.serialize("json", Person.objects.all())
Output :
{
"model": "store.person",
"fields": {
"first_name": "Douglas",
"last_name": "Adams",
"birth_date": "1952-03-11",
}
}
Now i want to return PersonLogs
into response JSON.
Expected Output :
{
"model": "store.person",
"fields": {
"first_name": "Douglas",
"last_name": "Adams",
"birth_date": "1952-03-11",
"personlogs": [['2015-06-09 15:42:58.861540'], ['2014-06-09 15:42:58.861540'], [2013-06-09 15:42:58.861540]]
}
}
I looked into official documentation but i did not get any help. link
It seems that you want to serialize
Person
with reverseForeignKey
relationship. Django's serializer doesn't support that. You'll have to use Django REST Framework, for e.g., as pointed out in comments by @DanielRoseman.But if you can compromise, the following solution will work.
Now, instead of serializing
Person
, you'll have to serializePersonLogs
, which will output this: