[Answer]-Django easy way to create model from a multiple models

1👍

You can use the Meta.get_all_field_names() method to get the list of Avg fields and then copy fields with the same names from A, B or C instance:

def create_avg(*args):
    data = {}
    for field_name in Avg._meta.get_all_field_names():
        if field_name != 'id':
            for instance in args:
                if hasattr(instance, field_name):
                    data[field_name] = getattr(instance, field_name)
                    break
    Avg.objects.create(**data)

And then call this function as:

avg_instance = create_avg(a_instance, b_instance, c_instance)

This solutions doesn’t handle ManyToMany fields but can be easily modified to do so.

Leave a comment