django如何处理可以是主键或对象的参数?
例如, MyModel.objects.filter(my_field=id)
有效,MyModel.objects.filter(my_field=my_obj)
也有效。
django是如何做到的? (我想复制它)
答案 0 :(得分:0)
此逻辑由django.db.models.fields.related_lookups
中的get_normalized_value
方法执行:
def get_normalized_value(value, lhs):
from django.db.models import Model
if isinstance(value, Model):
value_list = []
sources = lhs.output_field.get_path_info()[-1].target_fields
for source in sources:
while not isinstance(value, source.model) and source.remote_field:
source = source.remote_field.model._meta.get_field(source.remote_field.field_name)
try:
value_list.append(getattr(value, source.attname))
except AttributeError:
# A case like Restaurant.objects.filter(place=restaurant_instance),
# where place is a OneToOneField and the primary key of Restaurant.
return (value.pk,)
return tuple(value_list)
if not isinstance(value, tuple):
return (value,)
return value
基本上,它检查值是否为Model
实例,如果是,则将其转换为相应的主键。