DJANGO PROJECT的INNER JOIN(选择相关)

时间:2017-12-07 17:51:35

标签: python sql django inner-join django-select-related

我想知道如何在django项目中运行这个sql代码:

> SELECT * FROM COLETA INNER JOIN TRANSDUTOR ON COLETA.id_transdutor =
> TRANSDUTOR.id_transdutor INNER JOIN USER ON TRANSDUTOR.id_user =
> USER.id_user

请注意,我有3个表(COLETA,TRANSDUTOR,USER),我想通过您的外键关联它们。

USER表与TRANSDUTOR表有一对多的关系,而TRANSDUTOR表与COLETA表有一对多的关系。

我看到了一些与Django相关的SELECT-RELATED,有人知道如何使用它吗?

models.py:

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(_('email address'), unique=True)
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=30, blank=True)
    date_joined = models.DateTimeField(_('date joined'), auto_now_add=True)
    is_active = models.BooleanField(_('active'), default=True)
    is_staff = models.BooleanField(_('staff'), default=True)
    avatar = models.ImageField(upload_to='dashboard/static/avatars/', null=True, blank=True)

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    class Meta:
        verbose_name = _('user')
        verbose_name_plural = _('users')

    def get_full_name(self):
        '''
        Returns the first_name plus the last_name, with a space in between.
        '''
        full_name = '%s %s' % (self.first_name, self.last_name)
        return full_name.strip()

    def get_short_name(self):
        '''
        Returns the short name for the user.
        '''
        return self.first_name

    def email_user(self, subject, message, from_email=None, **kwargs):
        '''
        Sends an email to this User.
        '''
        send_mail(subject, message, from_email, [self.email], **kwargs)


class UserManager(BaseUserManager):
    use_in_migrations = True

    def _create_user(self, email, password, **extra_fields):
        """
        Creates and saves a User with the given email and password.
        """
        if not email:
            raise ValueError('The given email must be set')
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, email, password=None, **extra_fields):
        extra_fields.setdefault('is_superuser', False)
        return self._create_user(email, password, **extra_fields)

    def create_superuser(self, email, password, **extra_fields):
        extra_fields.setdefault('is_superuser', True)
        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True.')

        return self._create_user(email, password, **extra_fields)


class Concessionaria(models.Model):
    nome = models.CharField(max_length=255)
    hp_inicio = models.DateTimeField('hp inicio')
    hp_fim = models.DateTimeField('hp fim')
    def __str__(self):
        return self.nome


class Cliente_has_concessionaria(models.Model):
    id_cliente = models.ForeignKey(User, on_delete=models.CASCADE)
    id_concessionaria = models.ForeignKey(Concessionaria, on_delete=models.CASCADE)


class Classificacao(models.Model):
    nome = models.CharField(max_length=255)
    id_concessionaria = models.ForeignKey(Concessionaria, on_delete=models.CASCADE)

    def __str__(self):
        return self.nome


class Transdutor(models.Model):
    data_instalacao = models.DateTimeField('Data instalacao')
    numero_serie = models.CharField(max_length=255)
    chave_api = models.CharField(max_length=25, default='', blank=False) #T TODO: precisamos verificar se KEY cadastrado existe em algum equipamento
    id_cliente = models.ForeignKey(User, on_delete=models.CASCADE)
    id_classificacao = models.ForeignKey(Classificacao, on_delete=models.CASCADE)
    parametro_a = models.FloatField(max_length=255, null=True)
    parametro_b = models.FloatField(max_length=255, null=True)
    hora_ponto_inicio = models.TimeField('Hora inicio') 
    hora_ponto_fim = models.TimeField('Hora fim')
    nome_io6 = models.CharField(max_length=255)
    nome_io7 = models.CharField(max_length=255, blank=True)
    nome_io8 = models.CharField(max_length=255, blank=True)
    nome_io9 = models.CharField(max_length=255, blank=True)
    nome_io10 = models.CharField(max_length=255, blank=True)
    nome_io11 = models.CharField(max_length=255, blank=True)
    nome_io12 = models.CharField(max_length=255, blank=True)

    def __str__(self):
        return (self.chave_api)


class Servico(models.Model):
    descricao = models.CharField(max_length=255)
    valor = models.CharField(max_length=255)
    id_classificacao = models.ForeignKey(Classificacao, on_delete=models.CASCADE)

    def __str__(self):
        return self.descricao


class Coleta(models.Model):
    data_leitura = models.DateTimeField(null=True)  # TODO: MUdar isso depois
    io6 = models.FloatField(max_length=255, null=True)
    calculo_io6 = models.FloatField(max_length=255, null=True)
    media_io6 = models.FloatField(max_length=255, null=True)
    io7 = models.FloatField(max_length=255, null=True)
    calculo_io7 = models.FloatField(max_length=255, null=True)
    media_io7 = models.FloatField(max_length=255, null=True)
    io8 = models.FloatField(max_length=255, null=True)
    calculo_io8 = models.FloatField(max_length=255, null=True)
    media_io8 = models.FloatField(max_length=255, null=True)
    io9 = models.FloatField(max_length=255, null=True)
    io10 = models.FloatField(max_length=255, null=True)
    io11 = models.FloatField(max_length=255, null=True)
    io12 = models.FloatField(max_length=255, null=True)
    parametro_a = models.FloatField(max_length=255, null=True)
    parametro_b = models.FloatField(max_length=255, null=True)
    id_transdutor = models.ForeignKey(Transdutor, on_delete=models.CASCADE, null=True)

class Conta_contrato(models.Model):
    conta_contrato = models.CharField(max_length=255)
    id_cliente = models.ForeignKey(User, on_delete=models.CASCADE)


class Imposto(models.Model):
    nome = models.CharField(max_length=255)
    estado = models.CharField(max_length=255)
    valor = models.CharField(max_length=255)

    def __str__(self):
        return self.nome


class Constante(models.Model):
    nome = models.CharField(max_length=255)
    valor = models.CharField(max_length=255)

    def __str__(self):
        return self.nome

views.py:

def my_custom_bad_request_view(request):
    return render(request, '400.html', )


def my_custom_permission_denied_view(request):
    return render(request, '403.html', )


def my_custom_page_not_found_view(request):
    return render(request, '404.html', )


def my_custom_error_view(request):
    return render(request, '500.html', )


def index(request):
    return render(request, 'dashboard/index.html')


def do_change_password(request):
    if request.method == 'POST':
        form = PasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            user = form.save()
            update_session_auth_hash(request, user)  # Important!
            messages.success(request, 'Your password was successfully updated!')
            return redirect('change_password')
        else:
            messages.error(request, 'Please correct the error below.')
    else:
        form = PasswordChangeForm(request.user)
    return render(request, 'dashboard/change_password.html', {
        'form': form
    }) 

@login_required
def graficos(request):
    current_user = request.user
    first_name = User.objects.values_list('first_name', flat=True).filter(pk=current_user.id)
    last_name = User.objects.values_list('last_name', flat=True).filter(pk=current_user.id)
    date_joined = User.objects.values_list('date_joined', flat=True).filter(pk=current_user.id)
    context = {
        'last_name': last_name,
        'first_name': first_name,
        'date_joined': date_joined,
    }
    return render(request, 'dashboard/graficos.html', context)

def printa(request):

    coletas = Coleta.objects.all().order_by('-id')
    transdutores = Transdutor.objects.filter(id_cliente=request.user.id)
    io6_name = Transdutor.objects.values_list('nome_io6', flat=True).filter(id_cliente=request.user.id)
    io7_name = Transdutor.objects.values_list('nome_io7', flat=True).filter(id_cliente=request.user.id)
    io8_name = Transdutor.objects.values_list('nome_io8', flat=True).filter(id_cliente=request.user.id)

    parametros = Transdutor.objects.all().filter(id_cliente=request.user.id).order_by('-id')
    parametro_a = Transdutor.objects.values_list('parametro_a', flat=True).filter(id_cliente=request.user.id).order_by('-id').first()
    parametro_b = Transdutor.objects.values_list('parametro_b', flat=True).filter(id_cliente=request.user.id).order_by('-id').first()

    data = Coleta.objects.values_list('data_leitura', flat=True).filter(id_transdutor=1).order_by('-id')[:10]
    context = {

        'coletas': coletas,
        'transdutores': transdutores,
        'io6_name': io6_name,
        'io7_name': io7_name,
        'io8_name': io8_name,
        'parametro_a': parametro_a,
        'parametro_b': parametro_b,
        'data': data,
    }
    return render(request, 'dashboard/print.html', context)


def do_login(request):
    if request.method == 'GET':
        if request.user.is_authenticated():
            return render(request, 'dashboard/graficos.html')

    if request.method == 'POST':
        user = authenticate(username=request.POST['username'], password=request.POST['password'])
        if user is not None:
            if request.POST.get('lembrar', None) is not None:
                request.session.set_expiry(
                    60 * 60 * 24 * 30 * 12)  # Se selecionar o "lembrar-me" ficará logado por 1 ano
            login(request, user)
            return redirect('/graficos')
    return render(request, 'dashboard/login.html')


def do_logout(request):
    # return render(request, 'dashboard/logout.html')
    logout(request)
    return redirect('/login')


def consumo_mensal(request, *args, **kargs):
    mes = request.GET['mes']  # TODO: avaliar a forma como isso ta sendo feito
    dados = []
    transdutores = Transdutor.objects.filter(id_cliente=request.user.id)
    for t in transdutores:
        coletas = Coleta.objects.filter(id_transdutor_id=t.id, data_leitura__month=mes).order_by('data_leitura')
        for c in coletas:
            # soma os valores dos canais
            valores = [float(c.io6), float(c.io7), float(c.io8), float(c.io9), float(c.io10), float(c.io11),
                       float(c.io12)]
            soma = sum(valores)
            dia = int(c.data_leitura.day)
            adicionado = False
            for dado in dados:
                if dado['Dia'] == dia:
                    novo_valor = float(dado['Consumo']) + soma
                    dado['Consumo'] = "%.4f" % novo_valor
                    adicionado = True

            if not adicionado:
                dados.append({'Dia': dia, 'Consumo': "%.4f" % soma})

    return JsonResponse(dados, safe=False)


def consumo_mensal_por_setores(request, *args, **kargs):
    #io6_name = Transdutor.objects.values_list('nome_io6', flat=True).filter(chave_api="hab0001")
    data2 = [
        {'value': 2554, 'label': 'Industria'},
        {'value': 242, 'label': 'Oficina'},
        {'value': 3233, 'label': 'Suprimento'},
        {'value': 122, 'label': 'Outros Departamentos'}
    ]
    return JsonResponse(data2, safe=False)

def gasto_mensal(request, *args, **kargs):
    data3 = [
        {'Dia': '01', 'Valor': 51333},
        {'Dia': '02', 'Valor': 30222},
        {'Dia': '03', 'Valor': 20442},
        {'Dia': '04', 'Valor': 20123},
        {'Dia': '05', 'Valor': 32333},
        {'Dia': '06', 'Valor': 44963},
    ]
    return JsonResponse(data3, safe=False)


def gasto_mensal_por_setores(request, *args, **kargs):
    data = [
        {'value': 12.22, 'label': 'Industria'},
        {'value': 15.32, 'label': 'Oficina'},
        {'value': 12.12, 'label': 'Suprimento'},
        {'value': 51.30, 'label': 'Outros Departamentos'}
    ]
    return JsonResponse(data, safe=False)

谢谢你们。

1 个答案:

答案 0 :(得分:0)

这比你想象的要容易。在Django。 请注意这些链接。请

many to many in django model

many to one in django model