The join in Django can be done by accessing as an attribute, for example (assuming that the foreign key in the Validity model is called "parameter":
vigencias = Vigencia.objects.all() # Obtengo todas las vigencias
for vig in vigencias:
print(vig.parametro) # Imprime el objeto parametro
print(vig.parametro.descripcion) # Suponiendo que el modelo Parametro tiene un atributo descripcion
One optimization that can be done is to use the select_related()
(if you are sure that later you will use the foreign key), the first line would look like this:
vigencias = Vigencia.objects.all().select_related('parametro') # Obtengo todas las vigencias, y los parametros en la misma consulta.
This way you will not consult the database every time you want to obtain a parameter of a Validity.
In the same way you can access the attributes in a template:
<ul>
{% for vig in vigencias %}
<li>{{vig.parametro.descripcion}}</li>
{% endfor %}
</ul>
On the other hand, if you have multiple connected models you can also filter in a join, for example assuming that there are 3 models:
class Modelo1(models.Model):
nombre = models.CharField(max_length=30)
class Modelo2(models.Model):
descripcion = models.CharField(max_length=30)
mod1 = models.ForeignKey(Modelo1, on_delete=models.CASCADE)
class Modelo3(models.Model):
altura = models.CharField(max_length=30)
mod2 = models.ForeignKey(Modelo2, on_delete=models.CASCADE)
The following query can be made:
mod3 = Modelo3.objects.filter(mod2__mod1__nombre = "Rodrigo") # Hace un join de las 3 tablas y deja solo los que tiene un nombre igual a "Rodrigo"
For the case of wanting to obtain the validity of the major date, said minor date equal to today would be:
vigenciaMasReciente = Vigencia.objects.filter(fecha__lte = date.today()).select_related('parametro').order_by('-fecha')[0] # Primero filtro por fecha menor igual a hoy, despues ordeno de forma decreciente y por ultimo obtengo el primer elemento de ese QuerySet retornado
Here I leave you to read about the select_related ().
I hope I have helped you.