Retrieve objects from a model in django

0

I have the following related models.

class Puesto(models.Model):
nombre_depto = models.CharField(max_length=30)
clave_depto = models.CharField(max_length=30)
descripcion = models.CharField(max_length=30)

class Persona(models.Model):
nombre = models.CharField(max_length=30)
apellidos = models.CharField(max_length=30)
usr_clave = models.CharField(max_length=12)
puestos = models.ForeignKey(Puesto, blank=True, null=True)

And I'm trying to return the employees that belong to each of the positions that have been registered and get something like that.

I have been researching on how to recover related objects from each other and be able to show them in other templates, but so far I have not found anything useful to solve this problem.

    
asked by Ismael Caslop 17.08.2017 в 07:58
source

1 answer

0

I edit the answer according to your comment and try to be more specific in what you ask, and as much as possible put the code of what you have tried to do, to facilitate the answers.

I would do it like that, taking into account that you say that the list of positions is already:

  • Add ellink to the template where you show the posts:
  • Template posts

    <table>
        <thead>
            <tr>
                <th>Puesto</td>
            </tr>
        </thead>
        <tbody>
        {% for puesto in puestos %}
            <tr>
                <td><a href="{% url 'puestoPersonas' puesto.id %}">{{ puesto.nombre_depto }}</a></td>
            </tr>
       {% endfor %}
    

  • Create the url for the view where the people filtered by posts will be shown:
  • url.py

    url(r'^puestoPersonas/(?P<id_puesto>\d+)/$', puestosPersonas, name='puestoPersonas'),
    
  • Add this View:
  • Views.py

    def puestoPersonas(request, id_puesto):    
        personas = Persona.objects.distinct().filter(puestos=id_puesto)
        return render(request,'comosellame.html',{ 'personas':personas })  
    
  • Paint the data:
  • template

    <table>
        <thead>
            <tr>
                <th>EmpleadoId</td>
                <th>Nombres</td>
                <th>Apellidos</td>
                <th>Puesto</td>
                <th>Puesto ID</td>
            </tr>
        </thead>
        <tbody>
            {% for persona in personas %}
                <tr>
                    <td>{{ persona.id }}</td>
                    <td>{{ persona.nombre }}</td>
                    <td>{{ persona.apellidos }}</td>
                    <td>{{ persona.puestos.nombre_depto }}</td>
                    <td>{{ persona.puestos.id }}</td>
                </tr>
           {% endfor %}
       </tbody>
    </table>
    

    This way you get what Entendi you're looking for

        
    answered by 18.08.2017 / 04:24
    source