简体   繁体   English

如何让Django实现内部联接

[英]how to let django achieve inner join

there are two tables: 有两个表:

class TBLUserProfile(models.Model):
    userid = models.IntegerField(primary_key=True)
    relmusicuid = models.IntegerField()
    fansnum = models.IntegerField()

class TSinger(models.Model):
   fsinger_id = models.IntegerField()
   ftbl_user_profile = models.ForeignKey(TBLUserProfile, db_column='Fsinger_id')

I want to get Tsinger info and then order by TBLUserProfile.fansnum, I know how to write sql query: select * from t_singer INNER JOIN tbl_user_profile ON (tbl_user_profile.relmusicuid=t_singer.Fsinger_id) order by tbl_user_profile.fansnum , but I don't want to use model raw function. 我想获取Tsinger信息,然后通过TBLUserProfile.fansnum进行排序,我知道如何编写sql查询: select * from t_singer INNER JOIN tbl_user_profile ON (tbl_user_profile.relmusicuid=t_singer.Fsinger_id) order by tbl_user_profile.fansnum ,但我不这样做想要使用模型原始函数。 relmusicuid is not primary key otherwise I can use ForeignKey to let it work. relmusicuid不是主键,否则我可以使用ForeignKey使其起作用。 How can I use django model to achieve this? 我如何使用Django模型实现这一目标?

You can do like this : 您可以这样:

Tsinger.objects.all().order_by('ftbl_user_profile__fansnum')

For information about Django JOIN : https://docs.djangoproject.com/en/1.8/topics/db/examples/many_to_one/ 有关Django JOIN的信息: https : //docs.djangoproject.com/en/1.8/topics/db/examples/many_to_one/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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