我有一个用户个人资料模型。我想要一个新的模型方法给我一个关于完成配置文件的分数。例如:
Name 10%
Mobile 50%
Gender 10%
Website 10%
Location 10%
birth_date 10%
意思是,如果用户填写名称和移动,他们的个人资料将 60%完成。
有人能让我开始研究如何完成这样的事情吗?谢谢:
我的模特:
class Profile(UserenaLanguageBaseProfile):
""" Default profile """
GENDER_CHOICES = (
(1, _('Male')),
(2, _('Female')),
)
user = models.OneToOneField(User,
unique=True,
verbose_name=_('user'),
related_name='profile')
gender = models.PositiveSmallIntegerField(_('gender'),
choices=GENDER_CHOICES,
blank=True,
null=True)
mobile = models.CharField(max_length=32, blank=True)
website = models.URLField(_('website'), blank=True, )
location = models.CharField(_('location'), max_length=255, blank=True)
birth_date = models.DateField(_('birth date'), blank=True, null=True)
答案 0 :(得分:5)
一种方法可能是:
class Profile(UserenaLanguageBaseProfile):
#attributes
@property
def percentage_complete(self):
percent = { 'name': 10, 'mobile': 50, 'website': 10, 'location': 10, 'birth_date': 10, 'gender': 10}
total = 0
if self.gender:
total += percent.get('gender', 0)
if self.name:
total += percent.get('name', 0)
#and so on
return "%s"%(total)
然后profile.percentage_complete
为您提供完整性。由于您正在管理字典,因此您可以完全控制权重,并确保值为百分比。
答案 1 :(得分:0)
在一个项目中我必须在几个模型上计算模型完整性,这是我采用django信号来解决问题的方法。我们可以通过在django settings.py中定义模型来进一步采用这个例子。以及处理模型关系。
class UserProfile(UserenaLanguageBaseProfile):
complete_progress = { 'name': 10, 'mobile': 50, 'website': 10, 'location': 10, 'birth_date': 10, 'gender': 10}
# If this is too heavy best put this in a background task celery
@receiver(post_save)
def model_completeness_listener(sender, instance=None, created=False, **kwargs):
list_of_models = [UserProfile, CustomerProfile]
if sender in list_of_models:
complete_progress = 0.0
total_weight = 0.0
for field in instance.completeness:
try:
total_weight += instance.completeness[field]
if getattr(instance, field):
complete_progress += instance.completeness[field]
except AttributeError:
continue
overall_completeness = (complete_progress/total_weight) * 100
print "------------%s---------------" % (sender.__name__)
print "[progress weight : %d total weight : %d overall completeness : %d]" % (complete_progress, total_weight, overall_completeness)
print "-----------------------------"
使用overall_completeness百分比值执行某项操作,将其分配给配置文件模型或将其存储在其他位置