Simple Foreingkey in Django

75 views Asked by At

I´m begginer in Django.

I've a table in my database called 'produto' and each product belongs a group, I would like show the name that group in same 'for' in that appear the data of product.

models.py

from django.db import models

# Create your models here.
class Grupo(models.Model):
    codigo = models.AutoField(primary_key=True)
    nome = models.CharField(max_length=40, blank=True, null=True)
    tp_linha = models.IntegerField()
    data_alt = models.DateField(blank=True, null=True)
    data_inc = models.DateField(blank=True, null=True)
    status = models.CharField(max_length=1)

    class Meta:
        managed = False
        db_table = 'grupo'

class Produto(models.Model):
    codigo = models.AutoField(primary_key=True)
    nome = models.CharField(max_length=80)
    referencia = models.CharField(max_length=30)
    fabricante = models.IntegerField()
    quantidade = models.DecimalField(max_digits=17, decimal_places=6)
    preco_venda = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True)
    #...

    grupo_produto = models.ForeignKey(Grupo, related_name='grupo')
    def __str__(self):
        return self.nome

    class Meta:
        managed = False
        db_table = 'produto'

views.py

from django.shortcuts import render_to_response
from django.shortcuts import render

from .models import Servico, Produto, Grupo

# Create your views here.
def home(request):
    servicos = Servico.objects.using('mydatabase').all()
    produtos = Produto.objects.using('mydatabase').all()
    grupos = Grupo.objects.using('mydatabase').all()
    return render(request, 'home.html', {'servicos': servicos, 'produtos': produtos, 'grupos': grupos})

home.html

{% for Produto in produtos %}
    <tr>
        <td>{{Produto.codigo}}</td>
        <td>{{Produto.nome}}</td>
        <td>{{Produto.referencia}}</td>
        <td>{{Produto.fabricante}}</td>
        <td>{{Produto.quantidade}}</td>
        <td>R$ {{Produto.preco_venda}}</td>
        <td>{{Grupo.nome}}</td>
    </tr>
{% empty %}
    <span>Nenhum resultado encontrado</span>
{% endfor %}

I'am lost here, already appear some errors, but I don't know that do.

// UPDATE

I resolved follows way

from django.shortcuts import render_to_response
from django.shortcuts import render

from .models import Grupo, Produto

# Create your views here.
def home(request):
    produtos = Produto.objects.using('horus').raw('SELECT produto.codigo, produto.nome, produto.quantidade, produto.preco_venda, grupo.nome AS nome_grupo FROM produto LEFT JOIN grupo on (produto.grupo = grupo.codigo);');

    return render(request, 'home.html', {'produtos': produtos})

{% for Produto in produtos %}
        <tr>
            <td>{{Produto.codigo}}</td>
            <td>{{Produto.nome}}</td>
            <td>{{Produto.quantidade}}</td>
            <td>R$ {{Produto.preco_venda}}</td>
            <td>{{Produto.nome_grupo}}</td>
        </tr>
{% empty %}
    <span>Nenhum resultado encontrado</span>
{% endfor %}

https://docs.djangoproject.com/en/1.8/topics/db/sql/

I don't know if done right, I would like of tips.

2

There are 2 answers

4
Kyle L. On

try using

<td>{{Produto.grupo_produto.nome}}</td>

Does that help?

If that doesn't help try

<td>{{Produto.grupo.nome}}</td>

It may just be your related name.

0
bakkal On

Based on your models, it should be {{Produto.grupo_produto.nome}} so if that doesn't work the problem is elsewhere

(1054, "Unknown column 'produto.grupo_produto_id' in 'field list'")

This suggests that your DB doesn't have that grupo_produto = ForeignKey(...) field in it yet, check your DB and the DB migrations, that's where your problem is

P.S.:

No need to try {{Produto.grupo.nome}} the related_name='grupo' is for accessing the Produto objects from a Grupo object (products belonging to a group)

Which should have been named related_name='produtos' really, that way you can use grupo.produtos, which makes sense

The way you named related_name='grupo', it it would be grupo.grupo which doesn't make sense (bad name)