rayashi
rayashi

Reputation: 1851

Queryset of the foreign key Django

I have the model:

class Cliente(Endereco):
    email = models.EmailField()
    nome = models.CharField(max_length=60)

class Compromisso(models.Model):
    cliente = models.ForeignKey(Cliente)
    data = models.DateField()

How can I get the Queryset of de Client Model with Compromisso.date ?

Upvotes: 0

Views: 54

Answers (3)

rayashi
rayashi

Reputation: 1851

This helpe me:

clientes = Cliente.objects.filter(compromisso__data=data).distinct()

Thank you @Luis Masuelli

Upvotes: 0

brain storm
brain storm

Reputation: 31252

I am not sure if I understood your question correctly. You could get a queryset for all the Cliente objects and then iterate through them to get the Compromisso.date; something on this line:

queryset1=Clients.objects.all()
for cliente in queryset1:
     queryset=cliente.compromisso_set.all() # return all the compromisso objects
    # get all the date fields objects for all the query sets
     for c in queryset:
         date=c.data

Note: this is inefficient. unless you want to filter on a particular date, you try what Luis suggested

Upvotes: 0

Luis Masuelli
Luis Masuelli

Reputation: 12333

A queryset of Clients by filtering by compromisso.date (you put "data", i assume "date", as your question):

class Cliente(Endereco):
    email = models.EmailField()
    nome = models.CharField(max_length=60)

class Compromisso(models.Model):
    cliente = models.ForeignKey(Cliente)
    date = models.DateField()

queryset:

Cliente.objects.filter(compromisso_set__date=someDate)

Getting a Client and every date from associated "Compromisso"'s date is not possible without using .extra and doing your own sql. You can get them lazily as aClient.compromisso_set.all().only('date') for each Cliente (aClient) object.

Upvotes: 2

Related Questions