如何用随机值注释每个对象
how to annotate each object with random value
我想要带有随机注释的项目。
我试过这个:
items = Item.objects.all().annotate(random_value=Value(randint(1,6)),output_field=PositiveIntegerField()))
它是随机的,但对于 QuerySet 中的每个项目都是相同的。
但我想为每个项目设置不同的值...
有什么想法吗?
根据 @Willem Van Onsem 建议在 Django<3.2:
中是可能的
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
我想要带有随机注释的项目。
我试过这个:
items = Item.objects.all().annotate(random_value=Value(randint(1,6)),output_field=PositiveIntegerField()))
它是随机的,但对于 QuerySet 中的每个项目都是相同的。
但我想为每个项目设置不同的值...
有什么想法吗?
根据 @Willem Van Onsem 建议在 Django<3.2:
中是可能的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