gpt4 book ai didi

Django : Get specific columns from multiple tables

转载 作者:行者123 更新时间:2023-12-03 13:32:19 25 4
gpt4 key购买 nike

我需要从多个表中获取列,我该如何实现?

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') .但它说没有这样的领域。

我的模型课有什么需要改变的吗?

最佳答案

尝试这个:

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 )

关于 Django : Get specific columns from multiple tables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26110191/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com