如何知道Django模型中pk的值

时间:2018-08-15 19:31:51

标签: python django docker django-models

我现在正在学习Django,我想获得一个包含我的“数据库”和每行信息的ID / pk的表。现在我有这个:

型号:

class Car(HistoryBase):
plate = models.CharField(max_length=6, default='', verbose_name="Placa")
year = models.CharField(max_length=4, null=True, blank=True, default='', verbose_name="Año del auto")
model = models.CharField(max_length=20, null=True, blank=True, default='', verbose_name="Modelo del auto")
brand = models.CharField(max_length=20, null=True, blank=True, default='', verbose_name="Marca del auto")
color = models.CharField(max_length=20, null=True, blank=True, default='', verbose_name="Color del auto")

表格:

from ..core.forms import BootstrapModelForm
from .models import Car


class CarModelForm(BootstrapModelForm):
    class Meta:
      model = Car
      fields = '__all__'

查看:

from django.views.generic.edit import CreateView
from .models import Car
from .forms import CarModelForm

class CarDetailView(CreateView):
template_name = "cars_detail.html"
http_method_names = [u'get', u'post', ]
form_class = CarModelForm
model = Car
success_url = '/autos/{}'

def _get_car(self, *args, **kwargs):
    try:
        pk = int(self.kwargs.get('pk'))
        return Car.objects.get(pk=pk)
    except Exception:
        return None

模板:

<div class="col-sm-12">
  <div class="card">
    <div class="card-body">
      <div class="card-title"><h2>Listado de Autos</h2></div>
      <hr>
      <table id="tabla" class="table table-striped table-bordered" cellspacing="0" width="100%">
        <thead>
          <tr>
            <th>Numero</th>
            <th>Placa</th>
            <th>Marca</th>
            <th>Modelo</th>
            <th>Color</th>
          </tr>
        </thead>
        <tbody>
          {% for object in object_list %}
          <tr>
            **<td>{{ object.object_instance.pk }}</td>**
            <td>{{ object.plate }}</a></td>
            <td>{{ object.brand }}</td>
            <td>{{ object.model }}</td>
            <td>{{ object.color }}</td>
          </tr>
          {% endfor %}
        </tbody>
      </table>
    </div>
  </div>      
</div>

当我去浏览器查看表格时,“ numero”或ID列为空白,请提供一些帮助:)

1 个答案:

答案 0 :(得分:0)

pk只是Model实例的一个属性,因此您可以这样写:

<td>{{ object.pk }}</td>

该对象毕竟是一个模型实例。因此.pk属性是“ Django逻辑”添加的内容。

话虽如此,您可能应该修复Django CreateView(这也很奇怪,因为它看起来更像是ListView)。乍一看,_get_car(..)从未被调用过。自从您写了model=...以来,所有的逻辑都发生了。