How to create a custom model field inheriting ForeignKey in Django?

2

I want to build a custom field model that behaves like ForeignKey, but with some additional details.

This custom field will automatically register a document, passing the model name as a reference. Therefore, if I am registering a person, a document will be generated for it, and in this document the name of the model will be registered, in the Person case.

Example:

# esse model 'documento' seria utilizado como referencia para qualquer outro model
class Documento(models.Model):
    modelo = models.CharField(max_length=100)

class CustomDocForeignKey(models.ForeignKey):
    pass
    # relacionado a Documento
    # if este campo estiver vazio então crie um documento:
    #    nome_da_class_origem = ? # ex: Pessoa, Carro, ...
    #    doc = Documento.objects.create(modelo=nome_da_class_origem)
    #    return doc

class Pessoa(models.Model):
    documento = CustomDocForeignKey()

class Carro(models.Model):
    documento = CustomDocForeignKey()

class Animal(models.Model):
    documento = CustomDocForeignKey()

This custom model field would automatically generate a document for this person or car or animal if you do not have any documents. In addition, the name of the __class__.__name__ model is passed to be stored in the modelo field of the Documento class.

PS: The idea is for this field to be populated when the save () method is called, as is auto_now_add=True of the DateField field.

    
asked by anonymous 25.11.2015 / 19:18

0 answers