gpt4 book ai didi

python - 通过@property 中的字段列表获取相关对象的值

转载 作者:太空宇宙 更新时间:2023-11-03 23:52:38 25 4
gpt4 key购买 nike

我有两个这样的模型,具有以下字段:

Profile: 
-user(OTO Relation to User)
-address(OTO to Address)
-bio
-gender
...
Address:
-postal_code
-phone_number
-zip_code

我还有这个字段名称列表:

 my_list = ["bio","gender","address.postal_code","address.phone_number", "address.zip_code"]

最后我想创建这个@property:

@property
def is_complete_profile(self):
''' Checks if all the fields have been filled '''
if self.pk:
for field_name in my_list:
value = getattr(self,field_name)
if not value:
return False
return True
else:
return False

但是对于相关对象,这不是正确的方法,我得到了这个错误:

'Profile' object has no attribute 'address.postal_code'

如何使用此列表获取 Profile 对象的字段值和相关对象值?

注意:

I could solve this problem by using eval function, but because of this and this post, I preferred to throw this solution away.

最佳答案

与其让 Profile 窥探其同类的内部结构,不如为每个涉及的类提供一个 is_complete 属性(或方法)来确定实例是否完整,并让 Profile.is_complete_profile 访问这些属性以确定配置文件是否完整。

像这样的(未经测试)

class Address:

def is_complete(self):
fields = ["postal_code", "phone_number", "zip_code"]
for field in fields:
if not getattr(self, field):
return False
return True

class Profile:

def is_complete(self):
fields = ["bio","gender"]
for field in fields:
if not getattr(self, field):
return False
return True

@property
def is_complete_profile(self):
''' Checks if all the fields have been filled '''
if self.pk:
return self.is_complete() and self.address.is_complete()
return False

这样,如果 Address 字段的名称发生变化,则 Profile 无需更改,如果将其他对象添加到概念中,则只需要进行最小的更改的“完整性”。

关于python - 通过@property 中的字段列表获取相关对象的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58842724/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com