【问题标题】:How to retrieve first not null query set Django如何检索第一个非空查询集Django
【发布时间】:2021-10-29 01:51:52
【问题描述】:

我正在尝试在我的模型中获取唯一的非空数据。

例如:我有 Django 模型查询集数据,例如 {{id : 1,organisation :None},{id : 1,organisation :Google},{id : 2,organisation :None}}

预期结果: {{id : 1,organisation :Google},{id : 2,organisation :None}}

有什么方法可以根据 id,organization key 在 Queryset 中获取第一个非空值?

提前致谢。

【问题讨论】:

  • 分享你的模型。
  • 您可以将这样的过滤器添加到您的查询集中。 filter(organization__isnull=False)
  • 请提供足够的代码,以便其他人更好地理解或重现问题。

标签: django django-models django-rest-framework django-views django-queryset


【解决方案1】:

queryset = Model.objects.filter(organisation__isnull=False).values('id', 'organisation')

此查询应该可以工作,在示例中将您的 Model 名称放在 Model

【讨论】:

  • 这不符合我的要求,例如数据就像 = {{id : 1,organisation :None},{id : 1,organisation :None}} 它应该返回 {id : 1,组织:无}
  • 你想要not null value in Queryset based on the organization key,对吧?
  • 我需要 ** First Not Null Value** 基于 id 和 Organization 作为键(Id 将始终具有值,在某些情况下组织键将为空),我只需要获取 1 个查询集其中包含,例如,如果没有一个组织 ID 具有 ID 值,它应该返回 {id:1, organization:None}
  • instance = Model.objects.first() 我想这会对你有所帮助。 {'id': instance.pk, 'organisation':instance.organisation}
猜你喜欢
  • 2013-06-30
  • 2012-04-14
  • 2010-11-26
  • 2017-08-23
  • 2012-11-26
  • 2021-12-16
  • 2014-08-28
  • 2012-01-04
  • 1970-01-01
相关资源
最近更新 更多