Reputation: 1
I have a problem since four days and I hope that anyone can help me.
I have a model class A, which has User as Foreign Key and other attributes:
class A(models.Model):
user = models.ForeignKey(User)
....
In views.py:
objects_as_json = serializers.serialize('json', classA.objects.filter(user_id=2).order_by("-date"))
I got this as Response:
[{"model": "senApp.classA", "pk": 10, "fields": {"user": 2, "partner": null, "image": 6, "contest": 4, "action": 2, "date": "2016-07-29T09:35:59Z"}}, {"model": "sengApp.classA", "pk": 9, "fields": {"user": 2, "partner": 6, "image": 1, "contest": null, "action": 1, "date": "2016-07-29T09:23:43Z"}}]
So my question is, how can i add the username of the user in fields like this:
{"model": "senApp.classA", "pk": 10, "fields": {"user": 2, "partner": null, "image": 6, "contest": 4, "action": 2, "date": "2016-07-29T09:35:59Z", "username":}}
Thank you very much in advance for your answer.
Upvotes: 0
Views: 105
Reputation: 36815
You can set the keyword argument use_natural_foreign_keys
to True
:
objects_as_json = serializers.serialize(
'json',
classA.objects.filter(user_id=2).order_by("-date"),
use_natural_foreign_keys=True
)
Also see the django docs how you control what is returned as natural key
Upvotes: 1