折腾:
【未解决】Django的Serializer中如何序列化Script中的Author的Function Group
期间,想要去查询FunctionGroup中的字段members:
class FunctionGroup(TimestampedModel): members = models.ManyToManyField(User)
用代码:
joinedScriptGroup = FunctionGroup.objects.get(members__contains=curUser, function=FunctionGroup.TYPE_VALUE_SCRIPT)
其中curUser是当前的User的对象
结果出错:
File "/Users/crifan/dev/dev_root/company/xxx/projects/xxx/server/xxx/apps/script/serializers.py", line 30, in to_representation joinedScriptGroup = FunctionGroup.objects.get(members__contains=curUser, function=FunctionGroup.TYPE_VALUE_SCRIPT) File "/usr/local/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py", line 394, in get clone = self.filter(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py", line 836, in filter return self._filter_or_exclude(False, *args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py", line 854, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1253, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1277, in _add_q split_subq=split_subq, File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1215, in build_filter condition = self.build_lookup(lookups, col, value) File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1076, in build_lookup raise FieldError('Related Field got invalid lookup: {}'.format(lookup_name)) django.core.exceptions.FieldError: Related Field got invalid lookup: contains
搜:
django.core.exceptions.FieldError: Related Field got invalid lookup: contains
想起来了,其中双下划线__是可以用来获取字段的
所以试了试:
joinedScriptGroup = FunctionGroup.objects.get(members__id=curUser.id, function=FunctionGroup.TYPE_VALUE_SCRIPT)
然后可以了,可以查询到
FunctionGroup中多个User类型的members中,其中某个member的id是curUser.id
的对象了。
前端返回了:
注:
更多查询的用法参见官网:
转载请注明:在路上 » 【已解决】Django中查询model中字段是数组对象出错:django.core.exceptions.FieldError: Related Field got invalid lookup: contains