考虑以下:
status = queryset.values('status').annotate(count=Count('status'))
Run Code Online (Sandbox Code Playgroud)
其中statusfield 是CharFieldwith choices。这将产生一个包含status数据库值及其计数的字典列表。
有没有办法聚合status并显示其显示值?我已经查找了我可能可以模拟的代码_get_FIELD_display,但重复框架的内部代码感觉有点黑客。
作为我的模型类之一的成员函数,我有一个is_visible(self, user)返回布尔值的方法。根据定义,它将请求用户(DjangoUser模型)作为输入。
我希望能够根据对此方法的响应来过滤查询集。如何使用此函数作为查询集过滤器?
对于上下文,这是我的is_visible实现:
def is_visible(self, user):
if self.status.status_internal == "open":
return True
if self.owner == user:
return true
participations = Participation.objects.filter(event__id=self.id, participant__id=user.id)
if len(participations) > 0:
return True
if self.status.status_internal == "invite":
return True
return False
Run Code Online (Sandbox Code Playgroud) 我有这样的代码:
for m in MyModel.objects.filter(...):
mo = MyOtherModel.objects.get(myOtherField=m.myField)
print("{:s}{:s}".format(m, mo))
Run Code Online (Sandbox Code Playgroud)
这是低效的,因为查找mo需要对数据库进行新的查询。
为了避免这种情况,我正在考虑使用prefetch_related(Prefetch())or .annotate()。
第一个的问题是Prefetch()两个模型之间需要外键关系(它们没有)。
同样的事情.注释:
MyModel.objects.filter(...).annotate(moWithSameField=F('myField') == F(???))
Run Code Online (Sandbox Code Playgroud)
^ 即使我知道要写什么,这也是错误的???。
这可以吗?您可以根据任意查询预取完全不相关的内容吗?
我意识到我的标题有点复杂,但请允许我演示一下。我使用的是 Django 2.2.5 和 Python 3。以下是我当前正在使用的模型:
from django.db import models
from django.db.models import F
from django.contrib.postgres.indexes import GinIndex
from django.contrib.postgres.search import SearchVectorField, SearchVector, SearchQuery, SearchRank
class Thread(models.Model):
title = models.CharField(max_length=100)
last_update = models.DateTimeField(auto_now=True)
class PostQuerySet(models.QuerySet):
_search_vector = SearchVector('thread__type') + \
SearchVector('thread__title') + \
SearchVector('from_name') + \
SearchVector('from_email') + \
SearchVector('message')
###
# There's code here that updates the `Post.search_vector` field for each `Post` object
# using `PostQuerySet._search_vector`.
###
def search(self, text):
"""
Search posts using the indexed `search_vector` field. I …Run Code Online (Sandbox Code Playgroud) 我有一个像这样的文章模型
from django.contrib.contenttypes.fields import GenericRelation
from django.db import models
from hitcount.models import HitCountMixin, HitCount
class Article(models.Model):
title = models.CharField(max_length=250)
hit_count_generic = GenericRelation(
HitCount, object_id_field='object_pk',
related_query_name='hit_count_generic_relation')
Run Code Online (Sandbox Code Playgroud)
当我这样做时Article.objects.order_by('hit_count_generic__hits'),我会得到结果。但是当我这样做时
articles_by_id = Article.objects.filter(id__in=ids).annotate(qs_order=models.Value(0, models.IntegerField()))
articles_by_name = Article.objects.filter(title__icontains='sports').annotate(qs_order=models.Value(1, models.IntegerField()))
articles = articles_by_id.union(articles_by_name).order_by('qs_order', 'hit_count_generic__hits')
Run Code Online (Sandbox Code Playgroud)
出现错误
ORDER BY 术语与结果集中的任何列都不匹配
我怎样才能实现这样的结合?我必须使用 union 而不是 AND 和 OR,因为我需要保留顺序。IE; articles_by_id 应该排在第一位,articles_by_name 应该排在第二位。
使用 Django hitcount 进行 hitcount https://github.com/thornomad/django-hitcount。点击数模型如下。
class HitCount(models.Model):
"""
Model that stores the hit totals for any content object.
"""
hits = models.PositiveIntegerField(default=0)
modified = models.DateTimeField(auto_now=True) …Run Code Online (Sandbox Code Playgroud) 下面2种情况在Django ORM操作上有什么区别吗?会有任何性能提升等吗?
obj.manytomanyfield.clear()
obj.manytomanyfield.add(1,2,3,4,5)
Run Code Online (Sandbox Code Playgroud)
和
obj.manytomanyfield.set([1,2,3,4,5])
Run Code Online (Sandbox Code Playgroud) 我有以下模型:
\nclass Bank(model.Model):\n name: models.CharField\n ....\nRun Code Online (Sandbox Code Playgroud)\n使用以下示例数据:
\n\xe2\x95\x94\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x97\n\xe2\x95\x91 Row ID, Name \xe2\x95\x91\n\xe2\x95\xa0\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\xa3\n\xe2\x95\x91 1, ABC \xe2\x95\x91\n\xe2\x95\x91 2, ABC \xe2\x95\x91\n\xe2\x95\x91 3, XYZ \xe2\x95\x91\n\xe2\x95\x91 4, MNO \xe2\x95\x91\n\xe2\x95\x91 5, ABC \xe2\x95\x91\n\xe2\x95\x91 6, DEF \xe2\x95\x91\n\xe2\x95\x91 7, DEF \xe2\x95\x91\n\xe2\x95\x9a\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x9d\nRun Code Online (Sandbox Code Playgroud)\n我想提取不同的银行名称,如下所示:
\n[(\'ABC\', 3), (\'XYZ\', 1), (\'MNO\', 1), (\'DEF\', 2)]\nRun Code Online (Sandbox Code Playgroud)\n我尝试使用 annotate 和 distect 但出现以下错误:
\nNotImplementedError: annotate() + distinct(fields) is not implemented.\nRun Code Online (Sandbox Code Playgroud)\n我还遇到了以下问题:
\n\n其中有关于使用的答案models.Count(\'name\', distinct=True),但它返回重复的值。\n我如何使用 Django ORM 处理这个问题?
我有一个具有以下结构的 Django 模型:
class BBPerformance(models.Model):
marketcap_change = models.FloatField(verbose_name="marketcap change", null=True, blank=True)
bb_change = models.FloatField(verbose_name="bestbuy change", null=True, blank=True)
created_at = models.DateTimeField(verbose_name="created at", auto_now_add=True)
updated_at = models.DateTimeField(verbose_name="updated at", auto_now=True)
Run Code Online (Sandbox Code Playgroud)
我希望Avg每 3 天对对象进行一次聚合函数。
例如,我编写一个查询集,每天或使用类似TruncDay函数的东西进行此聚合。
queryset = BBPerformance.objects.annotate(day=TruncDay('created_at')).values('day').annotate(marketcap_avg=Avg('marketcap_change'),bb_avg=Avg('bb_change')
Run Code Online (Sandbox Code Playgroud)
如何获得 3 天间隔的聚合值的查询集以及该间隔第二天的索引?
我想将一个相当复杂的子查询加入到 Django ORM 查询集中:
结果查询应该是这样的:
select id from webshop_product
left outer join (
select product_id, count(extra_col) as quantity from (
select product_id, col1 as extra_col from xyz where x = 123 and y = 456
union
select product_id, col2 as extra_col from abc where a = 234 and y = 534
) as t1
) as t2 on t2.product_id = webshop_product.id
Run Code Online (Sandbox Code Playgroud)
左外连接子句中的连接子查询非常复杂,它涉及从不同表的联合进行聚合,我无法将其写在ORM中。我尝试在 ORM 中编写它,但是我无法在不同的表上实现 UNION...所以我想将它作为原始子查询加入,并注释数量列。
就像是:
Product.objects.all().join("my complex raw subquery")
Run Code Online (Sandbox Code Playgroud)
这在 Django ORM 中可能吗?
我们现在面临这样的情况,我想获得更有经验的用户\xe2\x80\x99s的意见。我们现在是 Django 4、Python 3.9。
\n目前的情况:
\n我们的系统已经在生产中运行了一段合理的时间,我们需要根据用户的选择在后端更改一些返回到我们的前端应用程序(Web、mobile\xe2\x80\xa6)的数据。
\n重要的是:目前无法选择前端方面的更改。
\n我们需要根据另一个表上现有或不对应的数据覆盖一个模型中的某些属性。
\n表格(Django 模型):
\nAgentSearch(该数据每天都会被 ETL 过程替换)
\n代理(代理可以定义的可选数据)
\n对于我们现在的要求,所有查询集都将从 开始进行AgentSearch。这个想法是获取Agent数据,而不是AgentSearch每次有代理链接到数据时就获取数据。
今天我们得到这样的结果:
\nAgentSearch.objects.all()
我知道像这样注释新列会更容易:
\n # using a different attribute name\n NEW_member_first_name=Case(\n When(\n agent__id__isnull=True,\n then=F("member_first_name"),\n ),\n default=F("agent__first_name"),\n ),\nRun Code Online (Sandbox Code Playgroud)\n这将需要我们对前端进行更改。 …
django django-models django-orm django-views django-rest-framework