How to compare two values of two different classes in Django

Asked

Viewed 204 times

2

Hi, I’m new to Django and I have the following problem, I have two classes in Django one of them is :

class Apps(models.Model):
id = models.UUIDField(db_column='ID', primary_key=True)  # Field name made lowercase.
name = models.CharField(db_column='Name', max_length=255)  # Field name made lowercase.
appid = models.CharField(db_column='AppId', max_length=500, blank=True, null=True)  # Field name made lowercase.
publishtime = models.DateTimeField(db_column='PublishTime')  # Field name made lowercase.
published = models.BooleanField(db_column='Published')  # Field name made 

class Meta:
    managed = False
    db_table = 'Apps'

And the other is :

class Executionresults(models.Model):
id = models.UUIDField(db_column='ID', primary_key=True)  # Field name made lowercase.
taskid = models.UUIDField(db_column='TaskID')  # Field name made lowercase.
executionid = models.UUIDField(db_column='ExecutionID')  # Field name made lowercase.
appid = models.UUIDField(db_column='AppID')  # Field name made lowercase.
executingnodeid = models.UUIDField(db_column='ExecutingNodeID')  # Field name made lowercase.
status = models.IntegerField(db_column='Status')  # Field name made

I would like to know how to compare two values, if the "appid" of the table "Apps" is equal to the "appid" of the table "Executionresults" it has to return me the "name" of the table "Apps".

I tried to do this live in index.html, but to no avail.

                  <table class="table table-striped up">
                        <thead>
                            <tr>
                                <th scope="col">#</th>
                                <th scope="col">Task ID</th>
                                <th scope="col">Inicio</th>
                                <th scope="col">Fim</th>
                                <th scope="col">Nome App</th>
                                <th scope="col">status</th>

                            </tr>
                        </thead>
                        <tbody>

                            {% for exe in executionresults %}
                            {% for app in apps %}
                            <tr>
                                <th scope="row"></th>
                                <td>{{ exe.taskid }}</td>
                                <td>{{ exe.starttime }}</td>
                                <td>{{ exe.stoptime }}</td>

                                {% if exe.appid == app.targetappid %}
                                    <td>{{ return app.name }}</td>
                                {%endif%}


                                {% if exe.status == 1 %}    
                                <td style="text-align: center;"class="alert alert-danger" role="alert">Desencadeado <i class="fa fa-check" style="font-size:16px"></i></td>

                                {%elif exe.status == 2 %}
                                <td style="text-align: center;"class="alert alert-success" role="alert">Iniciado <i class="fa fa-check" style="font-size:16px"></i></td>

                                {%elif exe.status == 3 %}
                                <td style="text-align: center;"class="alert alert-success" role="alert">Na fila <i class="fa fa-check" style="font-size:16px"></i></td>

                                {%elif exe.status == 4 %}
                                <td style="text-align: center; "class="alert alert-warning" role="alert">Abortar iniciado <i class="fa fa-exclamation" style="font-size:20px"></i></td>

                                {%elif exe.status == 5 %}
                                <td style="text-align: center; "class="alert alert-warning" role="alert">Abortando <i class="fa fa-exclamation" style="font-size:20px"></i></td>

                                {%elif exe.status == 6 %}
                                <td style="text-align: center;"class="alert alert-danger" role="alert">Abortado <i class="  fa fa-close" style="font-size:20px"></i></td>

                                {% elif exe.status == 7 %}  
                                <td style="text-align: center;"class="alert alert-success" role="alert">Finalizado com sucesso  <i class="fa fa-check" style="font-size:16px"></i></td>

                                {%elif exe.status == 8 %}
                                <td style="text-align: center;"class="alert alert-danger" role="alert">Falha! <i class="    fa fa-close" style="font-size:20px"></i></td>

                                {%elif exe.status == 9 %}
                                <td style="text-align: center; "class="alert alert-warning" role="alert">Pulou <i class="fa fa fa-exclamation" style="font-size:20px"></i></td>

                                {%elif exe.status == 10 %}
                                <td style="text-align: center;"class="alert alert-danger" role="alert">Tente novamente <i class="fa fa-close" style="font-size:20px"></i></td>

                                {%elif exe.status == 11 %}
                                <td style="text-align: center;"class="alert alert-danger" role="alert">Erro! <i class="     fa fa-close" style="font-size:20px"></i></td>

                                {%elif exe.status == 12 %}
                                <td style="text-align: center;"class="alert alert-danger" role="alert">Restabelecer <i class="  fa fa-close" style="font-size:20px"></i></td>

                                {%else%}
                                <td>{{ exe.status }}</td>
                                {%endif%}       
                            </tr>
                            {% endfor %}
                            {% endfor %}
                        </tbody>
                    </table>

My ultimate goal is to bring the tasks from the Executionresults table, but this table does not show the name of the app, and I need to show it to the user, so I need to make this union of tables.

1 answer

1


Is there a specific reason you’re using Uuidfield? If not, you’d better establish a relationship between the two Apps and Executionresults models. An example used in Jango’s own documentation of this is the following: A waiter is attached to a restaurant, and to make this relationship is made:

class Restaurant(models.Model):
    serves_hot_dogs = models.BooleanField(default=False)
    serves_pizza = models.BooleanField(default=False)

    def __str__(self):
        return "%s the restaurant" % self.place.name

class Waiter(models.Model):
    restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE)
    name = models.CharField(max_length=50)

The field restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE) guard in the waiter’s class, to which restaurant he relates.

In the case of your code, this line:

appid = models.UUIDField(db_column='AppID')  # Field name made lowercase.

Would be exchanged for that line:

appid = models.ForeignKey(Apps, on_delete=models.CASCADE)

So, you wouldn’t need to put those two Fors that you mounted

{% for exe in executionresults %}
{% for app in apps %}

Instead you would only traverse the executionresults objects and access them as follows:

 exe.appid.name

View:

from django.shortcuts import render
from models import Executionresults

def view_results(request):
    return render(request, 'index.html', {'executionresults': Executionresults.objects.all()})

Template:

 {% for exe in executionresults %}
    exe.appid.name
 {% endfor %}

Other comments:

  • Your html has a lot of programming logic. Django uses the standard MVT(Model-View-Template), you showed here your Models( the Apps and Executionresults classes) and your template (index.html) the view would be the part, python code, to put the programming logic (ifs, elses and other possible manipulations).
  • Does Django automatically generate id fields for models, note that your Apps and Executionsresults classes are with (models.Models)? It is because they inherit several characteristics of the standard models of Django, this is one of them.

Reference:

https://docs.djangoproject.com/pt-br/2.1/topics/db/examples/one_to_one/

  • Thank you so much for your help, I’ll make these adjustments and see what I can do.

  • Hello Fabíola, it would be possible to perform this configuration inside the view ?

  • A foreing key (Restaurant = models.Foreignkey(Restaurant, on_delete=models.CASCADE)) has to be in the model. In the view you send the Execution Results objects to your html template: return render(request, 'index.html', {'executionresults': Executionresults.objects.all()})

  • I edited the answer, I don’t know if it was very clear so anything just talk :)

  • Thanks again for the return Fabíola, just one more question, when I put this field in the models I can’t access the page anymore, I get an error . " column Executionresults.appidexe_id does not exist LINE 1: ...ults"." Taskid", "Executionresults"." Executionid", "Execution... " Even after giving a migrate and makemigrations the error continues.

  • 1

    I managed to solve Fabíola, I just reset my Migrations and it worked, I thank you again for your attention.

Show 1 more comment

Browser other questions tagged

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