django

时间:2018-03-21 11:31:41

标签: sql django orm django-rest-framework django-queryset

我同时有疑问和问题,我有两个不同的模型,像这样的项目

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

1 个答案:

答案 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]