How to create a custom model field by inheriting Foreignkey in Django?

Asked

Viewed 262 times

2

I’m looking to build a custom model field that behaves like Foreignkey, only with a few additional details.

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

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()

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

PS: the idea is that this field be filled in when calling the save() method, as well as the auto_now_add=True country DateField.

  • In this case you wouldn’t need to inherit from Foreignkey, just use a field in the templates that are Foreignkey for the document. document = models.Foreignkey(Customdoc) 1. Uses mixin not to repeat itself.. inside the mixin init of it passes a class to be recorded.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.