Niladry Kar
Niladry Kar

Reputation: 1203

How to perform reverse relation in django?

This is my models:

class Journal(models.Model):
    Start_Date = models.DateField(default=datetime.date(2018,4,1),blank=False)
    End_Date = models.DateField(default=datetime.date(2019,3,31),blank=False)
    Date = models.DateField()
    By = models.ForeignKey(ledger1,on_delete=models.CASCADE,related_name='Debitledgers')
    To = models.ForeignKey(ledger1,on_delete=models.CASCADE,related_name='Creditledgers')
    Debit = models.DecimalField(max_digits=10,decimal_places=2)
    Credit = models.DecimalField(max_digits=10,decimal_places=2)

I want to filter the journal objects within the "Start_Date" and "End_Date" of the journal model...

I mean to say The "Date" in journal must be between the "Start_Date" and "End_Date" of journal...

This might me a stupid question to ask...But, as I am learning django, its not easy for me...

Can anyone tell me how to do this???

Thank you in advance

Upvotes: 0

Views: 51

Answers (1)

neverwalkaloner
neverwalkaloner

Reputation: 47354

Try to use F expression like this:

Journal.object.filter(journals__Start_Date__gt=F('Date'), journals__End_Date__lt=F('Date'))

Actually it's not clear what exacly Selectdate model do. If you create it for filtering purpose only, you can remove it and use ORM without it:

Journal.object.filter(Date__gt=some_date_start, Date__lt=some_date_end)

As for updated question you can do this:

Journal.object.filter(Start_Date__gte=F('Date'), End_Date__lte=F('Date'))

Upvotes: 3

Related Questions