您好我在Django中制作后端服务器,用于存储来自应用的用户数据。 以下是我的模特。
class Subscriber(models.Model):
subId = models.IntegerField(max_length=20,unique=True,blank=False)
Name = models.CharField(max_length=25,blank=True)
class SMS(models.Model):
subscriberId = models.ForeignKey(Subscriber, null=False)
epochTime = models.IntegerField(null = False)
time = models.CharField(max_length= 250 ,blank = False)
class Call(models.Model):
subscriberId = models.ForeignKey(Subscriber, null=True)
epochTime = models.IntegerField(null = False)
time = models.CharField(max_length= 50 ,blank = False)
Date = models.CharField(max_length= 50 ,blank = False)
我需要写一个Django查询,我将给予subscriberId和Django将返回我使用来自Call和SMS的该用户的数据(基本上想要使用Join)。 早些时候我已经在mysql中应用了它。
select * from Server_Text JOIN (Server_Call) ON (Server_SMS.subscriberId_id = 11 and Server_Call.subscriberId_id = 11) ;
其中Server是我的mysql数据库。
答案 0 :(得分:0)
当你使用Django时,你不应该考虑连接和SQL查询;关键是模型层将这些抽象出来。您只想获得订阅者,然后按照关系获取短信和呼叫信息:
subscriber = Subscriber.objects.get(subId=my_subscriber_id)
print subscriber.sms_set.all() # all SMSs for that subscriber
print subscriber.call_set.all() # all Calls for that subscriber
如果你这么做很多,你可以在初始查询中使用prefetch_related('sms', 'call')
来提高效率。