user3638474
user3638474

Reputation: 11

Left join with django framework

I have these models:

class PartidosFifa(models.Model):
    Partido = models.IntegerField(max_length=11, default=0)
    PaisL = models.CharField(max_length=250)
    Local = models.IntegerField(max_length=11, default=0)
    Visita = models.IntegerField(max_length=11, default=0)
    PaisV = models.CharField(max_length=250)
    Resultado = models.CharField(max_length=250, default="No jugado")
    Fecha = models.DateField()
    Estadio = models.CharField(max_length=500)
    Jugado = models.CharField(max_length=5, default="No")
    def __unicode__(self):
        return unicode(self.Partido)

class PartidosUsuarios(models.Model):
    idUsuario = models.ForeignKey(User)
    idFifa = models.ForeignKey(PartidosFifa)
    idPartido = models.CharField(max_length=20)
    UPaisL = models.CharField(max_length=250)
    ULocal = models.IntegerField(max_length=11, default=0)
    UVisita = models.IntegerField(max_length=11, default=0)
    UPaisV = models.CharField(max_length=250)
    UResultado = models.CharField(max_length=250)
    Puntos = models.IntegerField(max_length=11, default=0)
    Capturado = models.CharField(max_length=10, default="No")
    def __unicode__(self):
        return unicode(self.idPartido)

I need to make partidosFifa table show all the records that have and show the results that you have on the table partidosUsuarios but may or may not have records in this table. in sql would be something like:

Select PartidosFifa.PaisL, PartidosFifa.PartidosFifaV, PartidosUsuarios.ULocal, PartidosUsuarios.UVista FROM PartidosFifaLEFT JOIN PartidosUsuarios ON PartidosFifa.Partido = PartidosUsuarios.idFifa

How would be written with django framework?

Upvotes: 1

Views: 79

Answers (1)

schillingt
schillingt

Reputation: 13731

With the Django ORM you don't actually write out the joins. You can help it determine the most efficient query and in this case you'd want to use prefetch_related as below.

partidos_fifa_set = PartidosFifa.objects.prefetch_related('partidosusuarios_set')

What this does is it will fetch all of the records PartidosUsuarios for each PartidosFifa record. To access it you'd loop through them as below:

for partidos_fifa in partidos_fifa_set:
    for partidos_usuarios in partidos_fifa.partidos_usuarios_set.all():
        # Do something with partidos_usuarios
        pass

Here are the docs for more reading.

Upvotes: 1

Related Questions