Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

439
Visualizações
Django: how store multiple data types to the same model field

I want to create a database model somewhat similar to the example below:

enter image description here

The idea is that User (or any model) can have multiple different features (or whatever) with different values. Feature can be anything, for example integer (salary), date (birthdate), or multiple selection (competences like C, Python, etc.). To keep the database design simple, I've tried an approach where I have only one Feature table which has optional choices via Choice table, instead of having separate database table for each feature type. User selection for feature value is stored to a User_has_Feature table "value" field, which is a CharField which can store multiple different data types, like integer, date, choice, multiple choice etc.

My question is, how can I validate all data so that it validates against the field data type, and also shows everything correctly in admin or UI (having different UI widgets for different types)?

I've tried an approach where I store the field type for each feature to Field table, which can be CharField, IntegerField, DateField, etc. Then in User_has_Feature model clean() I can dynamically validate against the field type, for example:

FIELDS = {
    'DateField': DateField,
    'IntegerField': IntegerField,
    etc.
}

def clean(self):
    class_ = FIELDS.get(self.feature.field)
    if class_ in [DateField, IntegerField, ...]:
        field = class_()
        field.clean(self.value)
    elif class_ in [ModelChoiceField, ModelMultipleChoiceField]:
        etc.

This approach works fine for validation, but it isn't helping for admin widgets and also data is always handled as a string, instead of integer, date, list, etc. So I've started to investigate option to create a custom ValueField model field, which inherits CharField, and would store all the data as a string to the database, but would change the widget and data type (to_python) dynamically for the value. No success so far, everything I try seems to go overly complex.

For me this seems to be quite common need, thus I would expect that some "easy" solution already exist. Or then I need to try different approach with the database design altogether.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You can use Django Content Types Framework docs

The main idea is that you can create dedicated classes (models) to your features, and CTF could help you to link features to the User (in your case). I'm using this for linking different models to the Logging model and each logging instance contains a direct link to the needed model instance that it logs.

UPDATE:

Ok, in Django terms we need:

  1. Use ManyToMany for relation User<->Features. You can define this field as features in the user model. So it will be simple calling in the future, like: user.features.all(). Managing related features will be also simple.
  2. Your clean method is correct: you are mapping string names of the str types of fields with classes. It's ok.
  3. Use this trick to make the same mapping but on the admin's side forms
class OurModelAdmin(admin.ModelAdmin):
    
    ...

    def formfield_for_dbfield(self, db_field, **kwargs):
        
        if db_field.name == 'Multiple':
            kwargs['widget'] = forms.CheckboxSelectMultiple
        
        # mapping is here

        return super(OurModelAdmin, self).formfield_for_dbfield(db_field,**kwargs)

    ...
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda