Django: Two different child classes point to same parent class

前端 未结 4 1152
名媛妹妹
名媛妹妹 2021-02-16 00:15

I have a model Person which stores all data about people. I also have a Client model which extends Person. I have another extending model OtherPe

4条回答
  •  情话喂你
    2021-02-16 00:52

    As mentioned in a comment already, there is an open ticket for this very question: https://code.djangoproject.com/ticket/7623

    In the meanwhile there is a proposed patch (https://github.com/django/django/compare/master...ar45:child_object_from_parent_model) which not using obj.__dict__ but creates an dictionary with all field values cycling over all fields. Here a simplified function:

    def create_child_from_parent_model(parent_obj, child_cls, init_values: dict):
        attrs = {}
        for field in parent_obj._meta._get_fields(reverse=False, include_parents=True):
            if field.attname not in attrs:
                attrs[field.attname] = getattr(parent_obj, field.attname)
        attrs[child_cls._meta.parents[parent_obj.__class__].name] = parent_obj
        attrs.update(init_values)
        print(attrs)
        return child_cls(**attrs)
    
    person = Person.objects.get(id=)
    client = create_child_from_parent_model(person, Client, {})
    client.save()
    

    If you want to create a sibling:

    client_person = getattr(person, person._meta.parents.get(Person).name)
    other_person = create_child_from_parent_model(person, OhterPerson, {})
    other_person.save()
    

    This method has the advantage that methods that are overwritten by the child are not replaced by the original parent methods. For me using the original answers obj.__dict__.update() led to exceptions as I was using the FieldTracker from model_utils in the parent class.

提交回复
热议问题