我有以下型号:
class TradeDetails(models.Model):
created_timestamp = models.DateTimeField(db_column='CREATED_TIMESTAMP', primary_key=True)
trade_name = models.CharField(db_column='TRADE_NAME', max_length=45)
trade_image = models.CharField(db_column='TRADE_IMAGE', max_length=500, blank=True, null=True)
class Meta:
managed = False
db_table = 'TRADE_DETAILS'
class TradeNotifications(models.Model):
client_id = models.CharField(db_column='CLIENT_ID', primary_key=True, max_length=15)
created_timestamp = models.DateTimeField(db_column='CREATED_TIMESTAMP')
updated_timestamp = models.DateTimeField(db_column='UPDATED_TIMESTAMP', blank=True, null=True)
platform_notification = models.IntegerField(db_column='PLATFORM_NOTIFICATION', blank=True, null=True)
sms_notification = models.IntegerField(db_column='SMS_NOTIFICATION', blank=True, null=True)
email_notification = models.IntegerField(db_column='EMAIL_NOTIFICATION', blank=True, null=True)
caller_notification = models.IntegerField(db_column='CALLER_NOTIFICATION', blank=True, null=True)
caller_id = models.IntegerField(db_column='CALLER_ID', blank=True, null=True)
client_confirmation = models.IntegerField(db_column='CLIENT_CONFIRMATION', blank=True, null=True)
device_id = models.CharField(db_column='DEVICE_ID', max_length=256, blank=True, null=True)
platform = models.CharField(db_column='PLATFORM', max_length=15, blank=True, null=True)
ip_address = models.CharField(db_column='IP_ADDRESS', max_length=50, blank=True, null=True)
expired = models.IntegerField(db_column='EXPIRED', blank=True, null=True)
trade_sent = models.IntegerField(db_column='TRADE_SENT', blank=True, null=True)
class Meta:
managed = False
db_table = 'TRADE_NOTIFICATIONS'
unique_together = (('client_id', 'created_timestamp'),)
我想使用以下sql查询在同一个数据库的另一个表上执行左连接:
SELECT TRADE_DETAILS.TRADE_NAME来自TRADE_NOTIFICATIONS LEFT JOIN TRADE_DOTAILS在TRADE_NOTIFICATIONS.CREATED_TIMESTAMP = TRADE_DETAILS.CREATED_TIMESTAMP
是否有更多像Django一样的方式,或者我应该使用raw SQL?
在阅读了一些答案后,我试图这样做:
TradeNotifications.objects.using('tradenotifications').all().values_list('trade_name', 'trade_details_created_timestamp')
但它引发了一个错误:
django.core.exceptions.FieldError: Cannot resolve keyword 'trade_name' into field. Choices are: caller_id, caller_notification,
答案 0 :(得分:0)
如果外键与Django ORM等模型之间没有某种关系,则无法连接表。模型之间必须存在关系。
这种关系不必在数据库中,如果它在模型中定义就足够了,但我认为这不适用于您的TradeDetails和TradeNotifications模型。您可以使用client_id
字段;您将其从CharField()
更改为ForeignKey()
。当您只读取数据库并对其进行反向工程并将其用作非托管模型时,这尤其有用。