如何用随机值注释每个对象

问题描述

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

我试过了:

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

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

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

有什么想法吗?

解决方法

根据 @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,function='RAND',**extra_context)

       def as_oracle(self,function='DBMS_RANDOM.VALUE',**extra_context)

       def as_sqlite(self,**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