Change a field of the parent class in the Django models

0

I have a parent class where I have an attribute that I want to modify according to the child class:

class Service(models.Model):
   # otros atributos
   SERVICE_TYPE = {
       'None': 'Unknown service type',
       'visa': 'Visa',
   }
   service_type = None

   def get_service_type(self):
       if self.service_type:
           return self.service_type
       else:
           return self.SERVICE_TYPE['None']

And I have several classes that inherit from this, one of them is the following:

class Visa(Service):
    # atributos de esta clase

The problem is that when I create an object of type Visa the attribute service_type of the parent class Service is never modified (it is always None). I have tried to modify the method save of Model and also modify it directly in the view to create and it does not work.

modifying the save method:

class Visa(Service):
    # atributes
    def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
    self.service_type = 'visa'
    return super(Visa, self).save(force_insert, force_update, using, update_fields)

modifying the attribute in the view:

class ServiceCreateView(generic.CreateView):
    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.service_type = 'visa'
        return super(ServiceCreateView, self).form_valid(form)
    
asked by Reinier Hernández Ávila 09.11.2018 в 20:53
source

1 answer

0

Reading the Django documentation on Model inheritance I found a way to be able to access the value of the parent class. This is how the models would look:

models.py

class Service(models.Model):
    # otros atributos
    SERVICE_TYPE = {
        'None': 'Tipo de servicio desconocido',
        'visa': 'Visado',
        'passport': 'Pasaporte',
    }
    service_type = None

    def get_service_type(self):
        if self.service_type:
            return self.SERVICE_TYPE[self.service_type]
        else:
            return self.SERVICE_TYPE['None']

class Visa(Service):
    # atributos de la clase Visa
    service_type = 'visa'

class Passport(Service):
    # atributos de la clase Passport
    service_type = 'passport'

Then the template would look like this:

templates / index.html

{% if service.visa %}
    {{ service.visa.get_service_type }}
{% elif service.passport %}
    {{ service.passport.get_service_type }}
{% else %}
    {{ service.get_service_type }}
{% endif %}

Showing Visa if the object is of the class Visa or shows Passport if it is an instance of the class Passport . If you do not belong to any of these classes, then it shows Unknown service type .

    
answered by 10.11.2018 / 17:01
source