我的 Django 项目中有以下模型。
class State(models.Model):
state_name = models.CharField(max_length=30, unique=True)
state_code = models.CharField(max_length=30, unique=True)
class District(models.Model):
district_name = models.CharField(max_length=50)
district_code = models.CharField(max_length=30)
state_obj = models.ForeignKey(State)
我想填充地区列表以及 state_obj 并将其发送到前端。 我正在使用序列化并尝试
serializers.serialize("json", District.objects.all())
并获得以下格式的结果
{"fields": {"state_obj": 23, "district_name": "NANDURBAR", "district_code": "NANDURBAR"}, "model": "adaxial_core.district", "pk": 665}
django中是否可以获取state_obj整个对象而不是id。
我期望的输出是这样的。
{"fields": {"state_obj": {id:1,state_name:'X',state_code:'Y'}, "district_name": "NANDURBAR", "district_code": "NANDURBAR"}, "model": "adaxial_core.district", "pk": 665}
想要尝试在不对结果集应用额外循环的情况下执行此操作。
有没有办法做到同样的事情
最佳答案
我认为这是不可能的,它已在 Django ticket 中得到解决(并被拒绝)。就在最近。如果依赖项是您的用例的一个选项,那么使用 Django Rest Framework(或我从未使用过的 tatypie)中的序列化器可能没问题。否则我想你必须用代码来做到这一点。
这里引用 last comment关于这个问题:
Unless theres a more fundamental addressing of the serialization API, aimed at making it generally usable and extendable for Web APIs I don't see any value in pushing the scope of the serializers as they now stand. Right now the use case for them should be for fixture loading and saving and nothing else. There are better tools out there for generally extendable serialization schemes (REST framework, tastypie, etc).
Django 的 select_related()
有助于避免额外的 SQL 命中,因此至少会提高一点性能。
关于python - Django 获取外键整个对象而不仅仅是 id(主键),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29781169/