Doubt at ManyToManyFields Django

-1

I'm new to Django and I'm just learning several things, let's say I have the following model where I have the Person, Car and Loan classes, a person in a loan can select several cars

class Persona(models.Model):
    nombre = models.CharField(max_length=200, null=False, blank=False)
    DNI = = models.PositiveIntegerField()

    def __str__(self):
        return self.nombre

class Coche(models.Model):

    opciones_color = (
        ('p01','Azul'), 
        ('p02','Rojo'), 
        ('p03','Verde'), 
        ('p04','Negro'), 
        ('p05','Blanco'), 
        ('p06','Gris')
    )
    color = models.CharField(max_length=3, choices = opciones_color)
    placa = models.CharField(max_length=6, null=False, blank=False)
    matricula = models.CharField(max_length=200, null=False, blank=False)

    def NombreCompleto(self):
        cadena = "Coche: {0} ---  Color: {1}"
        return cadena.format(self.placa, self.color)

    def __str__(self):
        return self.NombreCompleto()

class Prestamo(object):
    persona = models.ForeignKey(Persona, null=False, blank=False, on_delete=models.CASCADE)
    coche = models.ManyToManyField(Coche)
    fecha_pedido = models.DateField()

Obviously Person and Car would have more fields but for the purposes of the question it is not necessary to place them

my question is, how can I do that if I have 2 people registered and 3 cars and person 1 rents car 1 and car 2 then when person 2 goes to rent only appears car 3 because only you show car 3 at the time of selecting.

    
asked by Sebastian Moncada Duque 05.01.2018 в 04:09
source

1 answer

0

First get a list of the pk of the cars that are on loan

pks_coches_prest = Prestamo.objects.all().values("coche__pk").distinct()

now we get cars excluding those that have been borrowed

 coches_disponibles = Coche.objects.all().exclude(pk__in=pks_coches_prestados)
    
answered by 15.01.2018 в 22:45