INNER JOIN有三种型号的DJANGO RF

时间:2018-04-08 19:00:00

标签: django-models django-rest-framework django-views inner-join django-queryset

我的模特:

Model

我需要在这三个表之间建立一个连接,我需要一个带有字段machine_name的列表,它位于Action表中,基于机器的resetter_uuid。

class Machine(models.Model):
    machine_uuid = models.UUIDField(default=uuid.uuid4,unique=True)
    machine_created_date = models.DateTimeField(default=timezone.now)
    machine_name = models.CharField(max_length=50, null=True, default=None, blank=True)
    machine_time_up = models.CharField(max_length=10, null=True, default=None, blank=True)
    resetter_uuid = models.ForeignKey(Resetter, to_field="resetter_uuid", db_column="resetter_uuid", related_name='Resetters', on_delete=models.CASCADE, null=True)

    class Meta:
        db_table = 'Machine'

class Resetter(models.Model):
    resetter_uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
    resetter_created_date = models.DateTimeField(default=timezone.now)
    class Meta:
        db_table = 'Resetter'

class Action(models.Model):
    action_uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
    action_created_date = models.DateTimeField(default=timezone.now)
    action_change_port = models.PositiveSmallIntegerField(null=True, default=None)
    action_reset_machine = models.PositiveSmallIntegerField(null=True, default=None)
    machine_uuid = models.ForeignKey(Machine, to_field="machine_uuid", db_column="machine_uuid", related_name='Machines', on_delete=models.CASCADE)
    action_status = models.BooleanField()

    class Meta:
        db_table = 'Action'

使用MySQL我已经用这种方式解决了查询:

SELECT 
    m.machine_name
FROM
    machine m
INNER JOIN
    resetter r
ON
    m.resetter_uuid =r.resetter_uuid
INNER JOIN
    xem_api.action a
ON
    a.machine_uuid = m.machine_uuid 
WHERE
    m.resetter_uuid    = '5b94e54e7fd644359374146fe78eaea4' and a.action_status = true and a.action_reset_rig = 1;

我在视图中使用了 prefetch_related() select_related(),但是没有成功,获得该结果的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

我相信连接将与select_related / prefetch_related一起使用。请尝试下面的代码。记住select_related用于查询单个字段(关系的一侧),预取用于查询多个字段。

Machine.objects.select_related('Resetters').prefetch_related('Machines).all()

您可以通过向设置文件添加日志记录配置来仔细检查连接是否正常。添加以下代码,执行查询,并检查日志。

LOGGING = {
    'version': 1,
    'filters': {
        'require_debug_true': {
            '()': 'django.utils.log.RequireDebugTrue',
        }
    },
    'handlers': {
        'console': {
            'level': 'DEBUG',
            'filters': ['require_debug_true'],
            'class': 'logging.StreamHandler',
        }
    },
    'loggers': {
        'django.db.backends': {
            'level': 'DEBUG',
            'handlers': ['console'],
        }
    }
}