简体   繁体   中英

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 ?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM