Modify the value of a field of a model depending on the date - Django

1

I have a model like this:

class EdicionPrograma(models.Model):
   nombre_programa = models.ForeignKey(Programa)
   edicion = models.CharField(
       verbose_name="Edicion",
       blank=False,
       max_length=100
   )
   curso = models.CharField(
       max_length=255,
       verbose_name="Curso",
       blank=False
   )
   fecha_inicio = models.DateField(
       verbose_name="Fecha de inicio",
       blank=False
   )
   fecha_fin = models.DateField(
       verbose_name="Fecha de fin",
       blank=False
   )
   edicion_para_empresa=models.BooleanField(
       default=False,
       verbose_name="¿Empresa?",
       blank=False
   )
   abierta = models.BooleanField(default=False)
   class Meta:
       verbose_name = u"Edición"
       verbose_name_plural = u"Ediciones"
       ordering = ['nombre_programa']

   def __str__(self):
       return "{}".format(self.edicion)'

And I need the open field to change its value to True or False depending on whether the date of the current day is > that date_fin.

Would someone know how to do it?

Thanks in advance.

    
asked by FangusK 23.02.2017 в 23:40
source

1 answer

1

If you want to change the value to all records, the easiest is to do a data migration, in which you will have to specify what you want to do. This is how you create the migration:

~$ python manage.py makemigrations --empty app_name

To learn more about how to set up the migration, see here

And in the function to migrate do something like this:

...
def migrar_booleanfield_abierta(apps, schema_editor):
    from django.db import models
    from django.utils import timezone
    EdicionPrograma = apps.get_model('app_name', 'EdicionPrograma')

    EdicionPrograma.objects.update(
        abierta=models.Case(
            models.When(fecha_fin__lt=timezone.now(), then=True)
        ), default=False
    )
...

The good thing about doing that is that your data is stored in the database, the bad thing is that it is only done once, so the second thing I recommend is to make a method in the model that tells you if you are open or not, as follows:

In models.py (after the str ) method:

@property
def abierta(self):
   from django.utils import timezone
   return self.fecha_fin < timezone.now()

With this method, I would work just like with the current field, the only thing is that I would have to delete the current field of abierta to use this, and I could not do querysets.

Some doubt or if something does not work, leave it in the comments.

    
answered by 24.02.2017 / 00:06
source