Irfan Harun
Irfan Harun

Reputation: 1059

Django: apply filter on field of related model which is in another database

I've two tables in two database, say Policy in DB_A and Quote in DB_B.

Policy has a field result_reference which is the id of Quote table in DB_B

policy in DB_A

class Policy(models.Model):
    result_reference = models.IntegerField()
    policy_date = models.DateTimeField()

Quote in DB_B

class Quote(models.Model):
    quote_type = models.IntegerField()
    policy_type = models.CharField(max_length = 100)
    policy_premium = models.IntegerField()

The policy type can be S for Single and M for Multiple I want to get the policies with policy date after 30 days along with policy_type=M

What I've tried

import datetime
start_date = datetime.datetime.now() + datetime.timedelta(30)
p = Policy.objects.using(default_database).filter(policy_date__gte=start_date)

But this returns policies that have policy_type S and M. How can I filter it for policy type M?

Upvotes: 0

Views: 355

Answers (1)

user8060120
user8060120

Reputation:

If i understand you well, you can try: take a list of the quotes with type M and filter the Policy by this list using in, and of cause you should apply valid using for each query.

m_quotes = Quote.objects.filter(policy_type='M').values_list('pk', flat=True)
m_quotes = list(m_quotes)
p = Policy.objects.using(default_database).filter(result_reference__in=m_quotes)

Upvotes: 1

Related Questions