我需要从多个表中获取列,我该如何实现?
UserLog
+------------+----------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+----------+------+-----+---------+----------------+
| log_id | int(11) | NO | PRI | NULL | auto_increment |
| time | datetime | NO | | NULL | |
| ip_address | char(15) | YES | | NULL | |
| event_id | int(11) | NO | MUL | NULL | |
| user_id | int(11) | NO | MUL | NULL | |
+------------+----------+------+-----+---------+----------------+
Events
+-------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+----------------+
| event_id | int(11) | NO | PRI | NULL | auto_increment |
| description | varchar(200) | NO | | NULL | |
+-------------+--------------+------+-----+---------+----------------+
这是我的models.py
class Events(models.Model):
event_id = models.AutoField(primary_key=True,verbose_name="Event id")
description = models.CharField(max_length=200,verbose_name="Description")
def __unicode__(self):
return u"%d : %s" % (self.event_id, self.description)
class UserLog(models.Model):
log_id = models.AutoField(primary_key = True)
user = models.ForeignKey(User)
event = models.ForeignKey(Events,verbose_name = "event")
time = models.DateTimeField(default=datetime.now,blank=True)
ip_address = models.IPAddressField(null=True)
def __unicode__(self):
return u"%s (%s): %s" % (self.log_id, self.user, self.event)
我想做的
SELECT log_id,time,user_id,event_id,description from UserLog,Events where UserLog.event_id = Events.event_id
我试过了UserLog.objects.filter(event_id__event_id).values('log_id','time','user_id','event_id','description')
。但它没有说这些领域。
我的模型类中是否需要更改某些内容?
答案 0 :(得分:4)
试试这个:
UserLog.objects.filter(event_id=1).values('log_id',
'time',
'user_id',
'event_id',
'event__description')
或者,您可以使用select_related:
UserLog.objects.filter(event__id=1).select_related('event')
然后您将获得UserLog
个对象,并预先获取事件,这样您就可以在不触发其他查询的情况下访问该事件。
(另外,标准命名约定是调用模型Event
,而不是Events
)
答案 1 :(得分:0)
像这样使用select_related():
UserLog.objects.filter(event_id__event_id=1).select_related('event').values('log_id','time','user_id','event_id', 'event__description')
答案 2 :(得分:0)
dataStudent = Studentinfo.objects.select_related().values(
'country__countryname',
'state__statename',
'city__cityname',
'id','studentname',
'rollno',
'email',
'phoneno')
当您定义如下关注关系时, country__countryname
国家中的是字段的 name
city = models.ForeignKey(City, on_delete=models.CASCADE)
state = models.ForeignKey(State, on_delete=models.CASCADE)
country = models.ForeignKey(Country, on_delete=models.CASCADE)
和 countryname
是 country
表和
与 state__statename
和 city__cityname
和其他字段来自 Studentinfo
模型
这样可以给我以下结果