我有两个模型父,子
class Parent(models.Model):
id = models.IntegerField(...)
class Child(models.Model)
id = models.IntegerField(...)
parent = models.ForeignKey(Parent, ...)
wanted = models.CharField(default="yes")
我有一个查询集
parents = Parent.objects.all()
我想为基于子模型的父查询集注释一个字符字段
get_status(obj):
# complex function which returns string based on child onjects
children = Child.objects.filter(parent_id = obj.id)
if children.count() == 1:
return 'some'
if children.count() == 2:
return 'thing'
我想要这样的东西,如何将对象发送到 get_status() 函数。
queryset.annotate(status = Value(get_status(), output_field=CharField()))