【问题标题】:how to annotate each object with random value如何用随机值注释每个对象
【发布时间】:2021-03-27 16:48:31
【问题描述】:

我想要带有随机注释的项目。

我试过了:

items = Item.objects.all().annotate(random_value=Value(randint(1,6)),output_field=PositiveIntegerField()))

它是随机的,但对于 QuerySet 中的每个项目都是一样的。

但我希望每个项目都有不同的价值...

有什么想法吗?

【问题讨论】:

标签: django django-annotate


【解决方案1】:

根据@Willem Van Onsem 的建议,在 Django

def my_view(request):
    from django.db.models.expressions import Func
    from django.db.models.functions.mixins import (
        FixDecimalInputMixin, NumericOutputFieldMixin,
    )
    class Random(NumericOutputFieldMixin, Func):
       function = 'RANDOM'
       arity = 0

       def as_mysql(self, compiler, connection, **extra_context):
           return super().as_sql(compiler, connection, function='RAND', **extra_context)

       def as_oracle(self, compiler, connection, **extra_context):
           return super().as_sql(compiler, connection, function='DBMS_RANDOM.VALUE', **extra_context)

       def as_sqlite(self, compiler, connection, **extra_context):
           return super().as_sql(compiler, connection, function='RAND', **extra_context)

       def get_group_by_cols(self, alias=None):
           return []


    items = Item.objects.all().annotate(random_value=Round(Random()*5+1))

我是在 def my_view 中完成的,因为如果 3.2 变得稳定,我会删除它并添加全局 from django.models.db import Round

【讨论】:

    猜你喜欢
    • 2013-12-17
    • 2018-03-29
    • 1970-01-01
    • 1970-01-01
    • 2019-01-01
    • 1970-01-01
    • 2020-11-03
    • 1970-01-01
    • 2017-07-06
    相关资源
    最近更新 更多