I have 3 simple models:
我有3个简单的模型:
from django_better_admin_arrayfield.models.fields import ArrayField
class BuildItem(models.Model):
base = models.ForeignKey(Item, on_delete=models.CASCADE)
level = models.IntegerField(default=1)
mandatory_skills = ArrayField(models.IntegerField(null=True, blank=True), default=list)
class Item(BaseModel):
name = models.CharField(max_length=100)
class Skill(BaseModel):
item = models.ForeignKey(Item, on_delete=models.CASCADE, blank=True, null=True, related_name="skills")
effect = models.IntegerField(null=True, blank=True)
value = models.IntegerField(null=True, blank=True)
I would like to retrieve the sum of the value fields of the skills multiply by the level field of builditem, where the pk fields of the skills are in the mandatory_field list, if the effect field of skill is equal to 1.
如果技能的效果字段等于1,我想检索技能的值字段之和乘以构建项的级别字段,其中技能的主键字段在MANDIAND_FIELD列表中。
I wrote some code that works with for loop:
我编写了一些使用for循环的代码:
array_life = []
for builditem in BuildItem.objects.all():
for skill in builditem.base.skills.all():
if skill.pk in builditem.mandatory_skills:
if skill.effect == 1 and skill.value < 2:
array_life.append(skill.value * builditem.level)
sum_life = sum(array_life)
I would like to transform this code into a queryset.
(I tried many things but without success)
我想把这段代码转换成一个查询集。(我尝试了很多方法,但都没有成功)
Can anyone help me ?
有谁能帮帮我吗?
更多回答
优秀答案推荐
I'm not sure how django_better_admin_arrayfield works, but if it's anything like an m2m field, you could do something like:
我不确定django_better_admin_arrayfield是如何工作的,但如果它是类似于m2m字段的,你可以这样做:
sum_life = sum(Skill.objects.filter(
effect=1,
value__lt=2,
builditem__mandatory_skills__in=F('pk'),
).values_list('value', flat=True))
or
或
sum_life = Skill.objects.filter(
effect=1,
value__lt=2,
builditem__mandatory_skills__in=F('pk'),
).aggregate(Sum('value'))
更多回答
我是一名优秀的程序员,十分优秀!