Django associative table query

Asked

Viewed 120 times

0

Well... I’m trying to do an application on Django for residential energy consumption... I have three tables: Environment, Device and an associative, Appareil_environment where I have foreign keys to the two tables. My problem and the following, I want to make an inquiry where bring the appliances that are registered in an environment ex: Room = [television, Lamp, modem, air-conditioning...], Room = [lamp, fan, air-conditioning...]. I was able to make a query where it shows the devices you have in the environment, only at the time of rendering the template, which is shown a dictionary ex:{display__name : 'lamp'} and, not only the name of the device itself. Am I new to Django and would like to know how to perform this consultation with Django’s Orm? Thank you very much!

class Ambiente(models.Model):

    name = models.CharField(verbose_name='Nome do ambiente', max_length=100, blank=True)
    slug = models.SlugField(verbose_name='Atalho', blank=True, unique=True, max_length=100)
    created_at = models.DateTimeField(verbose_name='Criado em',auto_now_add=True)
    updated_at = models.DateTimeField(verbose_name='Atualizado em', auto_now=True)

    def __str__(self):
        return self.name

class Aparelho(models.Model):
    name = models.CharField(verbose_name='Nome do aparelho', max_length=100)
    slug = models.SlugField(verbose_name='Atalho', blank=True, max_length=100, unique=True)
    potencia = models.IntegerField(verbose_name='Potencia em watts', null=True, blank=True)
    created_at = models.DateTimeField(verbose_name='Criado em', auto_now_add=True)
    updated_at = models.DateTimeField(verbose_name='Atualizado em', auto_now=True)

    objects = AparelhoManager()

    def __str__(self):
        return self.name

class Aparelho_Ambiente(models.Model):
    
    STATUS_CHOICES = (
        (1, 'minutos/dia'),
        (2, 'horas/dia'),
    )
    
    ambiente = models.ForeignKey(Ambiente, verbose_name='Ambiente', related_name='ambientes', on_delete=models.deletion.DO_NOTHING)
    aparelho = models.ForeignKey(Aparelho, verbose_name='Aparelho', related_name='aparelhos', on_delete=models.deletion.DO_NOTHING)
    quantidade = models.IntegerField('Quantidade', default=0, blank=True,)
    tempo = models.IntegerField(verbose_name='Tempo de uso', null=True, blank=True)
    status = models.IntegerField(choices=STATUS_CHOICES, default=2, blank=True)
    created_at = models.DateTimeField('Criado em', auto_now_add=True)
    updated_at = models.DateTimeField('Atualizado em', auto_now=True)

View

def simulator(request, slug):
    context={}
    ambientes = Ambiente.objects.prefetch_related('ambientes').order_by('id')
    apps = Aparelho_Ambiente.objects.prefetch_related('ambientes','aparelhos').values(
        'aparelho__name'
    ).filter(ambiente__slug=slug)
    context = {

        'ambientes':ambientes,
        'apps':apps,
    }
    return render(request, 'aparelhos/simulador.html', context)

Template

{% for ambiente in ambientes %}
        <button class="tablink" onclick="openPage('{{ ambiente.name }}', this, 'red')"><a>{{ ambiente.name }}</a></button>
    
        <div id="{{ ambiente.name }}" class="tabcontent">
            {% for app in apps %}
                {{ app }}
            {% empty %}
                <p>Nenhum aparelho encontrado</p>
            {% endfor %}
        </div>
    {% endfor %}
  • Hello hello, share what you’ve tried.

  • I was able to make a query where I bring the devices you have in an environment, but when it comes to moving to the template, the data are showing how to add: {'aparelho__name':'fan'...}

  • def simulator(request, slug):&#xA; context={}&#xA; ambientes = Ambiente.objects.prefetch_related('ambientes').order_by('id')&#xA; apps = Aparelho_Ambiente.objects.prefetch_related('ambientes','aparelhos').values(&#xA; 'aparelho__name'&#xA; ).filter(ambiente__slug=slug)&#xA; context = {&#xA;&#xA; 'ambientes':ambientes,&#xA; 'apps':apps,&#xA; }&#xA; return render(request, 'aparelhos/simulador.html', context)

  • Edit your question and put that code plus the template being too big, just put the part where you have those variables to simplify.

  • It is already edited!

1 answer

0


Your solution is very close to the one that works, since you indicate that it already returns the expected, you only need to change a line in your html.

    {% for ambiente in ambientes %}
        <button class="tablink" onclick="openPage('{{ ambiente.name }}', this, 'red')"><a>{{ ambiente.name }}</a></button>
        <div id="{{ ambiente.name }}" class="tabcontent">
            {% for app in apps %}
                {{ app.aparelho__name }} <!-- <==== AQUI adicionas o que definiste no values 'aparelho__name' na tua consulta com o ORM de Django-->
            {% empty %}
                <p>Nenhum aparelho encontrado</p>
            {% endfor %}
        </div>
    {% endfor %}
  • Thanks! but I ended up changing the structure of the models... I removed the associative table, and added a Manytomanyfield in the Environment model relating to Apparatus model. I was a little impatient, but I really appreciate your attention. At some point I will redo to test your solution. Thank you, again!

Browser other questions tagged

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