0

I have written a simple code for calculating the percentage of profile complete. The way i have done does not covers the field which are a foreign key to the profile model. Here is how i have done

def calculate_profile_percentage(self, context):
    # fk related field are not here
    fields = {'full_name': 10, 'age': 10, 'city': 10, 'address': 10}
    completed_profile_percent = 0
    try:
        profile_instance = model_to_dict(Profile.objects.get(user_id=context.get('id')))
        print('profile get_instance', profile_instance)
        for field in profile_instance:
            print ("field", field)
            if fields.get(field) is not None:
                print("field found", field)
                completed_profile_percent += fields[field]
    except Profile.DoesNotExist:
        logger.error("Profile does not exist")
    print("completed_profile_percent", completed_profile_percent)
    return completed_profile_percent

This is a basic one but how do i handle fk related part either. Does anyone have better algorithm considering the Fk fields either?

Serenity
  • 3,884
  • 6
  • 44
  • 87
  • What's your question exactly? you don't get the foreign keys in model_to_dict or what? – Ken4scholars Apr 04 '19 at 14:39
  • my question is on how i fit fk fields like i have fitted the full_name, age and calculate the percentage based on whether those required fields are filled or not. – Serenity Apr 04 '19 at 14:43
  • you add the fields nested into it like `...'foreign_field': {'field1': 20...}`. Then use a nested DRF serializer to serialize the model and get the nested fields instead of using `model_to_dict` which will return the foreign keys and not the actual nested fields – Ken4scholars Apr 04 '19 at 14:50
  • Sorry i did not mention this before but the problem is I am using this function in django-channel and I am not using DRF instead I am using graphene – Serenity Apr 04 '19 at 14:53
  • Doesn't really matter. You can just use DRF as a library to do the serialization. Or you can write a custom model to dict serializer. Check this question https://stackoverflow.com/questions/21925671/convert-django-model-object-to-dict-with-all-of-the-fields-intact – Ken4scholars Apr 04 '19 at 15:18

0 Answers0