Django中的模型:
class Event(BaseModel):
id = models.AutoField(primary_key=True)
event_id = models.CharField(max_length=128, unique=True)
receiver = models.CharField(max_length=512)
class FireMonitor(BaseModel):
id = models.AutoField(primary_key=True)
event_id = models.CharField(max_length=128, unique=True)
status = models.IntegerField()
我需要从数据库中选择此数据:
select * from event e inner join fire_monitor f on e.event_id = f.event_id
我认为sqlalchemy代码:
event = orm.session.query(Event).join(Event.event_id == FireMonitor.event_id).all()
是否要更改Django orm?
答案 0 :(得分:0)
如果我对您的理解正确,那么您需要对方案进行一些更改。
class FireMonitor(BaseModel):
status = models.IntegerField()
class Event(BaseModel):
fire_monitor = models.ForeignKey(FireMonitor, on_delete=models.CASCADE)
receiver = models.CharField(max_length=512)
结果,FireMonitor与事件多对一关联。 (在此处https://docs.djangoproject.com/en/2.2/ref/models/fields/#django.db.models.ForeignKey了解更多信息) 现在,我们可以获得所有这样的事件:
events = Event.objects.all()
for event in events:
print(event.fire_monitor.status) # print fire_monitor status
P.S。我删除的字段“ id”。 (Django默认添加它们)