您可以从django中的子对象访问父字段吗?
tl; dr:我想表达[child.child_field_value,child.parent_field_value]
在django Child模型上,并获得['Alsatian'' ,'狗']
或类似。
上下文:我正在尝试为Django中的JSON API准备一个dict,这样我就有两个模型,评估
及其父charity> charity
。
在视图中,我过滤了所有符合某些参数的评估,然后使用评估列表中的dict comp secter.__ dict __。这个问题的重点,但是请告诉我您是否知道更好的练习!):
response = { 'evaluations': [{
key:value for key, value in evaluation.__dict__.items()
if key not in ['_state']} for evaluation in evaluations]}
但是我想要一种结合字段charity_name
和charity_abbreviation
的好方法慈善机构与该评估领域的其余部分。到目前为止两个字段。
但是我还没有弄清楚如何做到这一点,而且似乎最终会遇到一个非常混乱的东西,这在功能上并不理想,因为我宁愿数组是两个关键:值对其余的词典。
tl;dr: I want to express something like [child.child_field_value, child.parent_field_value]
on a Django child model and get an iterable like ['Alsatian', 'Dog']
or similar.
Context: I'm trying to prepare a dict for a JSON API in Django, such that I have two models, Evaluation
and its parent Charity
.
In the view I filter for all Evaluations meeting certain parameters, and then use a dict comp nexted in a list comp on evaluation.__dict__.items()
to drop Django's '_state' field (this isn't the focus of this question, but please tell me if you know a better practice!):
response = { 'evaluations': [{
key:value for key, value in evaluation.__dict__.items()
if key not in ['_state']} for evaluation in evaluations]}
But I want a good way to combine the fields charity_name
and charity_abbreviation
of each Evaluation's parent charity with the rest of that evaluation's fields. So far the best way I can find/think of is during the dict comp to conditionally check whether the field we're iterating through is charity_id
and if so to look up that charity and return an array of the two fields.
But I haven't figured out how to do that, and it seems likely to end up with something very messy which isn't isn't functionally ideal, since I'd rather that array was two key:value pairs in line with the rest of the dictionary.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论