我同时有疑问和问题,我有两个不同的模型,像这样的项目
PROJECT:TransactionMaster.models => TransactionMaster
class TransactionMaster(models.Model):
user = models.ForeignKey(User, on_delete=CASCADE)
trans_status = models.BooleanField()
trans_name = models.CharField()
PROJECT:TransactionDetails.models => TransactionDetail
from app.transactionMaster.models import TransactionMaster
class TransactionDetail(models.Model):
transaction = models.ForeignKey(TransactionMaster, on_delete=CASCADE)
current_status = models.IntegerField()
transdetail_name = models.CharField()
如何进行下一个sql查询
SELECT * FROM User as u inner join TransactionMaster as tm in u.id=tm.user_id inner join TransactionDetail as td in tm=td.transaction_id where tm.trans_status=td.current_status
和
SELECT * FROM TransactionMaster as tm inner join TransactionDetail as td in tm.id=td.transaction_id where tm.trans_status=td.current_status
我尝试第二个查询:
TransactionDetail.object.filter(TransactionMaster__id=transaction_id, trans_status=TransactionMaster__current_status)
请帮我解决这些疑问,请你回答我在不同项目的模特中我能做些什么。
感谢您的关注 Angel Rojas
答案 0 :(得分:0)
对于这两个查询,您似乎希望获得至少有一条TransactionMaster
条记录的TransactionDetail
条记录,其curent_status
等于trans_status
TransactionMaster
。
在Django中,这可能转化为:
from django.db.models import F
transaction_masters = TransactionMaster.objects.filter(transactiondetail__current_status=F('trans_status'))
对于第一个查询,看起来好像您对TransactionMaster
记录的用户感兴趣?要获取用户,只需从过滤后的transaction_masters
中提取它们。
users = [tm.user for tm in transaction_masters]