您可以从django中的子对象访问父字段吗?

发布于 2025-01-25 18:06:14 字数 755 浏览 1 评论 0原文

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_namecharity_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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文