Bring back multiple filtered Django Rest data

Asked

Viewed 160 times

0

Good morning, How do I bring multiple data from Django Rest, for example :

Primeiro resultado

instead of appearing the id of the students I want to bring the names... I don’t know if it’s possible but I hope it is... I’m using nuxt.js with vuetify.js, Django Rest framework and Django filter

<!-- frontend/pages/Index.vue -->
<template>
  <v-card class="mx-auto">
    <v-card-title>{{ evento.descricao }}</v-card-title>

    <v-card-text>
      <h3>Projeto : {{ projeto.descricao }}</h3>
      <div v-for="pp in participanteProjeto" :key="pp.id">
          <h3>Alunos : {{ pp.participante }}</h3>
      </div>
    </v-card-text>
  </v-card>
</template>

<script>
export default {
  head() {
    return {
      title: "View Alunos"
    };
  },
  async asyncData({ $axios, params }) {
    try {
      let evento = await $axios.$get(`/eventos/${params.id}`);

      let projeto = await $axios.$get(`/projetos/${evento.projeto}`);

      let participanteProjeto = await $axios.$get(`/participantes-projetos/?evento=${params.id}`);

      //let participantes = await $axios.$get(`/participantes/?grupo=${participanteProjeto.participante}`);

      return { evento, projeto, participanteProjeto };
    } catch (e) {
      return { evento: [], projeto: [], participanteProjeto: [] };
    }
  },
  data() {
    return {
      evento: {
        descricao: "",
        projeto: ""
      },
      projeto: {
        id: "",
        descricao: ""
      },
      participanteProjeto: {
        id: "",
        participante: ""
      }
    };
  }
};
</script>
# api/cadastros/views.py
from rest_framework import viewsets
from .serializers import ProjetoSerializer
from .serializers import ParticipanteSerializer
from .serializers import EventoSerializer
from .serializers import ParticipanteProjetoSerializer
from .models import Projeto
from .models import ParticipanteProjeto
from .models import Participante
from .models import Evento
from django_filters import rest_framework as filters


class ProjetoViewSet(viewsets.ModelViewSet):
    serializer_class = ProjetoSerializer
    queryset = Projeto.objects.all()


class ParticipanteViewSet(viewsets.ModelViewSet):
    serializer_class = ParticipanteSerializer
    queryset = Participante.objects.all()
    filter_backends = (filters.DjangoFilterBackend,)
    filter_fields = ('id', 'grupo')


class EventoViewSet(viewsets.ModelViewSet):
    serializer_class = EventoSerializer
    queryset = Evento.objects.all()


class ParticipanteProjetoViewSet(viewsets.ModelViewSet):
    serializer_class = ParticipanteProjetoSerializer
    queryset = ParticipanteProjeto.objects.all()
    filter_backends = (filters.DjangoFilterBackend,)
    filter_fields = '__all__'
from django.db import models

# Create your models here.


class Projeto(models.Model):

    MATEMATICA = 1
    CIENCIAS = 2

    MATERIA = (
        (MATEMATICA, 'Matemática'),
        (CIENCIAS, 'Ciências')
    )

    QTDMAXMIN = (
        (3, '3'),
        (4, '4'),
    (5, '5')
    )

    materia = models.IntegerField(choices=MATERIA)
    descricao = models.CharField(max_length=50)
    quantidade = models.IntegerField(choices=QTDMAXMIN)

    def __str__(self):
        return f'[{self.get_materia_display()}] - {self.descricao}'

    class Meta:
        verbose_name = "Projeto"
        verbose_name_plural = "Projetos"


class Participante(models.Model):

    SEXO = (
        ('F', 'Feminino'),
        ('M', 'Masculino')
    )

    GRUPOS = (
        ('1', 'GRUPO - 1 - CIENCIAS'),
        ('2', 'GRUPO - 2 - CIENCIAS'),
        ('3', 'GRUPO - 3 - CIENCIAS'),
        ('4', 'GRUPO - 4 - CIENCIAS'),
        ('5', 'GRUPO - 1 - MATEMATICA'),
        ('6', 'GRUPO - 2 - MATEMATICA'),
        ('7', 'GRUPO - 3 - MATEMATICA')

    )
    nome = models.CharField(max_length=200)
    email = models.EmailField(max_length=120)
    sexo = models.CharField(choices=SEXO, max_length=2)
    grupo = models.CharField(choices=GRUPOS, max_length=2)

    def __str__(self):
        return self.nome

    class Meta:
        verbose_name = "Participante"
        verbose_name_plural = "Participantes"


class Evento(models.Model):
    descricao = models.CharField(max_length=100)
    projeto = models.ForeignKey(
        to='cadastros.Projeto', on_delete=models.DO_NOTHING)

    def __str__(self):
        return self.descricao

    class Meta:
        verbose_name = "Evento"
        verbose_name_plural = "Eventos"

    def save(self, *args, **kwargs):
       super().save(*args, **kwargs)

       projetos = Projeto.objects.filter(pk=self.projeto_id).first()
       quantidade = projetos.quantidade
       for p in range(0, quantidade):
           ParticipanteProjeto.objects.update_or_create(evento=self,ordem=p+1)


class ParticipanteProjeto(models.Model):
    evento = models.ForeignKey(
        to='cadastros.Evento', 
        on_delete=models.CASCADE
        )
    ordem = models.IntegerField(default=0) 
    participante = models.ForeignKey(
        to='cadastros.Participante', 
        on_delete=models.DO_NOTHING,
        null=True,
        blank=True
        )

    def __str__(self):
        return f'{self.pk}'

    class Meta:
        verbose_name = "Participante Projeto"
        verbose_name_plural = "Participantes Projetos"

# api/cadastros/admin.py
from django.contrib import admin
from .models import Projeto
from .models import Participante
from .models import Evento
from .models import ParticipanteProjeto
# Register your models here.

@admin.register(Projeto)
class ProjetoAdmin(admin.ModelAdmin):
    list_display = ('descricao', 'materia')

@admin.register(Participante)
class ParticipanteAdmin(admin.ModelAdmin):
    list_display = ('id', 'nome')

class ParticipanteProjetoInLine(admin.TabularInline):
    model = ParticipanteProjeto

@admin.register(Evento)
class EventoAdmin(admin.ModelAdmin):
    list_display = ('descricao', 'projeto')
    inlines = [
       ParticipanteProjetoInLine
   ]

the whole code is here : mathematical science fair

1 answer

0

I managed to resolve this way my doubt :

at index.Vue :

<template>
  <v-card class="mx-auto">
    <v-card-title>{{ evento.descricao }<v-card-title>

    <v-card-text>
      <h3>Projeto : {{ projeto.descricao }}</h3>
      <div v-for="pp in participantes" :key="pp.id">
        <h3>Alunos : {{ pp.nome }}</h3>
      </div>
    </v-card-text>
  </v-card>
</template>

<script>
export default {
  head() {
    return {
      title: "View Alunos"
    };
  },
  async asyncData({ $axios, params }) {
    try {
      let evento = await $axios.$get(`/eventos/${params.id}`);

      let projeto = await $axios.$get(`/projetos/${evento.projeto}`);

      let participanteProjeto = await $axios.$get(
        `/participantes-projetos/?evento=${params.id}`
      );
      let participantes = await $axios.$get(
        `/participantes/?grupo=${params.id}`
      );
      //;

      return { evento, projeto, participanteProjeto, participantes };
    } catch (e) {
      return {
        evento: [],
        projeto: [],
        participanteProjeto: [],
        participantes: []
      };
    }
  },
  data() {
    return {
      evento: {
        descricao: "",
        projeto: ""
      },
      projeto: {
        id: "",
        descricao: ""
      },
      participanteProjeto: {
        id: "",
        participante: ""
      },
      participantes: []
    };
  }
};
</script>

I removed the comment from the participant Let and at the end of the url put /?grupo=${params.id} which means I had to add a new field on the back so I went to my models and added the following line in the attendees template :

 grupo = models.CharField(choices=GRUPOS, max_length=2)

and added the Choices, already tried to put the foreignkey only that it was depending on other things so I gave up on it and added these lines

GRUPOS = (
        ('1', 'GRUPO - 1 - CIENCIAS'),
        ('2', 'GRUPO - 2 - CIENCIAS'),
        ('3', 'GRUPO - 3 - CIENCIAS'),
        ('4', 'GRUPO - 4 - CIENCIAS'),
        ('5', 'GRUPO - 1 - MATEMATICA'),
        ('6', 'GRUPO - 2 - MATEMATICA'),
        ('7', 'GRUPO - 3 - MATEMATICA')

    )

so I started filtering through the group !

at the end of everything, it was like this img1 and added a note validation on front ;) ! ent. was just issuh, I don’t know if it’s right but I got it this way...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.