Django迭代通过unique_together设置的对象而没有pk

时间:2017-05-03 15:43:15

标签: python django

我正在尝试遍历传递给for模板标记的对象集。

# Views.py
@staff_member_required
def index(request):
    order_list = OrderInfo.objects.all()
    attribs = OrderInfo._meta.fields
    content_list = Content.objects.all()
    return render(request, 'orders/index.html', {'order_list': order_list, 'attribs': attribs, 'content_list': content_list})

但是,Content的模型有一个unique_together pk,所以我不能给它一个ID pk。

# orders/Models.py
class OrderInfo(models.Model):


order_id = models.AutoField(primary_key=True, unique=True)
    agent_id = models.ForeignKey(Agent, db_column='agent_id', null=False, blank=False, default=2)
    customer_id = models.ForeignKey(Customer, db_column='customer_id', null=False, blank=False, default=4)
    issue_date = models.DateField(blank=False, null=False, default='2017-01-01')
    issue_time = models.TimeField(blank=False, null=False)
    delivery_date = models.DateField(blank=False, null=False, default='2017-01-01')
    delivery_time = models.TimeField(blank=False, null=False)   

    def __str__(self):
        return str(self.order_id)

    class Meta:
        app_label = 'orders'
        db_table = 'orderinfo'

class Content(models.Model):
    content_id = models.AutoField(primary_key=True, unique=True)
    order_id = models.ForeignKey(OrderInfo, db_column='order_id')
    product_id = models.ForeignKey(Product, db_column='product_id')
    personalization = models.CharField(max_length=255, blank=False, null=False, default='')
    quantity_ordered = models.PositiveIntegerField(blank=False, null=False, default=1)
    discount = models.FloatField(blank=False, null=False, default=0.00)

    def __str__(self):
        return str(self.order_id + "|" + self.product_id)

    class Meta:
        app_label = 'orders'
        db_table = 'content'
        unique_together = (('order_id', 'product_id'),)

还有产品

# catalog/models.py
class Product(models.Model):
    product_id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=255, blank=False, null=False, default='Swiffer')
    color = models.CharField(choices=COLOR_CHOICES, max_length=255, blank=False, null=False, default='red')
    quantity_stocked = models.PositiveIntegerField(blank=False, null=False, default=1)
    personalization_limit = models.IntegerField(blank=False, null=False, default=8)
    price = models.FloatField(blank=False, null=False, default=20.00)

    def __str__(self):
        return str(self.product_id)

    class Meta:
        app_label = 'catalog'
        db_table = 'product'

由于Content没有ID pk,我在传递上下文并尝试循环时遇到错误:

OperationalError at /orders/
(1054, "Unknown column 'content.id' in 'field list'")

html代码是:

<!DOCTYPE html>
<html>
<head>
    <title>Orders</title>
    <style>
        table, th, td {
            border: 1px solid black;
        }
    </style>
</head>
<body>
    {% extends 'del3/base.html' %}

    {% block content %}
    <h1>Order List</h1>
    <table>
        <tr>
            {% for attrib in attribs|slice:":3" %}
            <th>{{attrib.name}}</th>
            {% endfor %}
            <th>recipient</th>
            {% for attrib in attribs|slice:"3:" %}
            <th>{{attrib.name}}</th>
            {% endfor %}
            <th>summary</th>
        </tr>
        {% for order in order_list %}
        <tr>
            <td>{{order.order_id}}</td>
            <td>{{order.agent_id}}</td>
            <td>{{order.recipient_id}}</td>
            <td>{{order.recipient_id.first_name}} {{order.recipient_id.last_name}}</td>
            <td>{{order.issue_date}}</td>
            <td>{{order.issue_time}}</td>
            <td>{{order.delivery_date}}</td>
            <td>{{order.delivery_time}}</td>
            <td>Agent {{order.agent_id}} {{order.agent_id.first_name}} in charge of Order {{order.order_id}} sent to Recipient {{order.recipient_id}} {{order.recipient_id.first_name}}</td>    
        </tr>
        {% endfor %}
    </table>
    <h1>Order Contents</h1>
    <table>
        <tr>
            <th>order id</th>
            <th>product id</th>
            <th>name</th>
            <th>color</th>
            <th>personalization</th>
            <th>quantity ordered</th>
            <th>discount</th>
        </tr>
        {% for content in content_list %}
        <tr>
            <td>{{content.order_id}}</td>
            <td>{{content.product_id}}</td>
            <td>{{content.product_id.name}}</td>
            <td>{{content.product_id.color}}</td>
            <td>{{content.personalization}}</td>
            <td>{{content.quantity_ordered}}</td>
            <td>{{content.discount}}</td>
        {% endfor %}
    </table>
    {% endblock %}
</body>
</html>

我知道这里的错误是Content没有id(Django需要循环访问某些内容,如果我是正确的),但由于unique_together已经是PK,我无法提供内容一个ID。有没有办法解决这个问题或绕过它?或者我错过了什么?

谢谢!

编辑:堆栈跟踪(对不起,这是我第一次询问Django!) 环境:

Request Method: GET
Request URL: http://127.0.0.1:8000/orders/

Django Version: 1.8.8
Python Version: 3.6.1
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'agents',
 'catalog',
 'del3',
 'customers',
 'orders')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'django.middleware.security.SecurityMiddleware')


Template error:
In template C:\Users\Gab De Jesus\Desktop\Mega\CS122Del3\del3\orders\templates\orders\index.html, error at line 52
   1054

   42 :     <table>



   43 :         <tr>



   44 :             <th>order id</th>



   45 :             <th>product id</th>



   46 :             <th>name</th>



   47 :             <th>color</th>



   48 :             <th>personalization</th>



   49 :             <th>quantity ordered</th>



   50 :             <th>discount</th>



   51 :         </tr>



   52 :          {% for content in content_list %} 



   53 :         <tr>



   54 :             <td>{{content.order_id}}</td>



   55 :             <td>{{content.product_id}}</td>



   56 :             <td>{{content.product_id.name}}</td>



   57 :             <td>{{content.product_id.color}}</td>



   58 :             <td>{{content.personalization}}</td>



   59 :             <td>{{content.quantity_ordered}}</td>



   60 :             <td>{{content.discount}}</td>



   61 :         {% endfor %}



   62 :     </table>


Traceback:
File "C:\Anaconda3\envs\django\lib\site-packages\django\core\handlers\base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Anaconda3\envs\django\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
  22.                 return view_func(request, *args, **kwargs)
File "C:\Users\Gab De Jesus\Desktop\Mega\CS122Del3\del3\orders\views.py" in index
  12.   return render(request, 'orders/index.html', {'order_list': order_list, 'attribs': attribs, 'content_list': content_list})
File "C:\Anaconda3\envs\django\lib\site-packages\django\shortcuts.py" in render
  67.             template_name, context, request=request, using=using)
File "C:\Anaconda3\envs\django\lib\site-packages\django\template\loader.py" in render_to_string
  99.         return template.render(context, request)
File "C:\Anaconda3\envs\django\lib\site-packages\django\template\backends\django.py" in render
  74.         return self.template.render(context)
File "C:\Anaconda3\envs\django\lib\site-packages\django\template\base.py" in render
  210.                     return self._render(context)
File "C:\Anaconda3\envs\django\lib\site-packages\django\template\base.py" in _render
  202.         return self.nodelist.render(context)
File "C:\Anaconda3\envs\django\lib\site-packages\django\template\base.py" in render
  905.                 bit = self.render_node(node, context)
File "C:\Anaconda3\envs\django\lib\site-packages\django\template\debug.py" in render_node
  79.             return node.render(context)
File "C:\Anaconda3\envs\django\lib\site-packages\django\template\loader_tags.py" in render
  135.         return compiled_parent._render(context)
File "C:\Anaconda3\envs\django\lib\site-packages\django\template\base.py" in _render
  202.         return self.nodelist.render(context)
File "C:\Anaconda3\envs\django\lib\site-packages\django\template\base.py" in render
  905.                 bit = self.render_node(node, context)
File "C:\Anaconda3\envs\django\lib\site-packages\django\template\debug.py" in render_node
  79.             return node.render(context)
File "C:\Anaconda3\envs\django\lib\site-packages\django\template\loader_tags.py" in render
  65.                 result = block.nodelist.render(context)
File "C:\Anaconda3\envs\django\lib\site-packages\django\template\base.py" in render
  905.                 bit = self.render_node(node, context)
File "C:\Anaconda3\envs\django\lib\site-packages\django\template\debug.py" in render_node
  79.             return node.render(context)
File "C:\Anaconda3\envs\django\lib\site-packages\django\template\defaulttags.py" in render
  162.             len_values = len(values)
File "C:\Anaconda3\envs\django\lib\site-packages\django\db\models\query.py" in __len__
  144.         self._fetch_all()
File "C:\Anaconda3\envs\django\lib\site-packages\django\db\models\query.py" in _fetch_all
  965.             self._result_cache = list(self.iterator())
File "C:\Anaconda3\envs\django\lib\site-packages\django\db\models\query.py" in iterator
  238.         results = compiler.execute_sql()
File "C:\Anaconda3\envs\django\lib\site-packages\django\db\models\sql\compiler.py" in execute_sql
  840.             cursor.execute(sql, params)
File "C:\Anaconda3\envs\django\lib\site-packages\django\db\backends\utils.py" in execute
  79.             return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\Anaconda3\envs\django\lib\site-packages\django\db\backends\utils.py" in execute
  64.                 return self.cursor.execute(sql, params)
File "C:\Anaconda3\envs\django\lib\site-packages\django\db\utils.py" in __exit__
  98.                 six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\Anaconda3\envs\django\lib\site-packages\django\utils\six.py" in reraise
  685.             raise value.with_traceback(tb)
File "C:\Anaconda3\envs\django\lib\site-packages\django\db\backends\utils.py" in execute
  64.                 return self.cursor.execute(sql, params)
File "C:\Anaconda3\envs\django\lib\site-packages\django\db\backends\mysql\base.py" in execute
  124.             return self.cursor.execute(query, args)
File "C:\Anaconda3\envs\django\lib\site-packages\MySQLdb\cursors.py" in execute
  250.             self.errorhandler(self, exc, value)
File "C:\Anaconda3\envs\django\lib\site-packages\MySQLdb\connections.py" in defaulterrorhandler
  50.         raise errorvalue
File "C:\Anaconda3\envs\django\lib\site-packages\MySQLdb\cursors.py" in execute
  247.             res = self._query(query)
File "C:\Anaconda3\envs\django\lib\site-packages\MySQLdb\cursors.py" in _query
  411.         rowcount = self._do_query(q)
File "C:\Anaconda3\envs\django\lib\site-packages\MySQLdb\cursors.py" in _do_query
  374.         db.query(q)
File "C:\Anaconda3\envs\django\lib\site-packages\MySQLdb\connections.py" in query
  292.             _mysql.connection.query(self, query)

Exception Type: OperationalError at /orders/
Exception Value: (1054, "Unknown column 'content.id' in 'field list'")

1 个答案:

答案 0 :(得分:0)

查看追溯电话

OperationalError at /orders/
(1054, "Unknown column 'content.id' in 'field list'")

我想您已尝试从id实例获取content字段,而不是您在模型中设置的content_id字段。

来自docs:

  

如果您想指定自定义主键,只需在其中一个字段中指定primary_key = True即可。如果Django看到你明确设置了Field.primary_key,它就不会添加自动id列。

因此,您已使用content.id覆盖content.content_id

由于您将id提供给primary_key=True字段,因此您不再拥有content_id字段。

尝试将id替换为content_id。 类似的东西:

{{ content.content_id }}

编辑:好的,您编辑了帖子..现在我可以看到问题了。

实际上,这是一个MySQL错误。

您可以查看: Django Models (1054, “Unknown column in 'field list'”)

此外: Unknown column '' in 'field list'. Django