I'm初學者在Django。簡單Foreingkey在Django
我有一個表在我的數據庫稱爲「produto」和每個產品所屬的組,我想節目的名字在該組中相同的「爲」在出現產品的數據。
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 %}
我'丟在這裏,已經出現了一些錯誤,但我不知道那樣做。
// UPDATE
我解決如下方式
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/
我不知道這樣做的權利,我想提示。
此外,如果您遇到錯誤,請提供錯誤的堆棧跟蹤您收到 –
- >我想顯示的名稱該組中相同的「爲」在出現產品的數據。 這是什麼意思? – Praneeth
您是否發現問題? – bakkal