我有一个问题已经四天了,我希望任何人都能帮助我。
我有一个模型类a,它具有User作为外键和其他属性:
类(models.Model):
user = models.ForeignKey(User)
....
在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"}}]
那么我的问题是,我如何在这样的字段中添加用户的用户名:
{"model": "senApp.classA", "pk": 10, "fields": {"user": 2, "partner": null, "image": 6, "contest": 4, "action": 2, "date": "2016-07-29T09:35:59Z", "username":}}
非常感谢您的回答
可以设置关键字参数use_natural_foreign_keys
为True
:
objects_as_json = serializers.serialize(
'json',
classA.objects.filter(user_id=2).order_by("-date"),
use_natural_foreign_keys=True
)
请参阅django文档如何控制返回的自然键