【问题标题】:Django Iterating through an object set with unique_together and no pkDjango 遍历一个具有 unique_together 且没有 pk 的对象集
【发布时间】:2017-05-03 15:43:14
【问题描述】:

我正在尝试遍历传递给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 has no id (如果我是正确的,Django 需要循环某些东西),但是由于 unique_together 已经是 PK,我不能给 Content 一个 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'")

【问题讨论】:

  • 发布完整的堆栈跟踪和您的实际代码。例如,您有一个元索引,但没有 product_id
  • 另外,错误与代码不匹配;错误提到了“id”字段,但您的代码有“content_id”。
  • 抱歉,添加了完整的代码和堆栈跟踪!
  • 你用的是什么版本的 django?
  • @LucasMoeskops Django 1.8

标签: python django


【解决方案1】:

查看回溯调用

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

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

来自文档:

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

所以,您已经用content.content_id 覆盖了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

【讨论】:

    猜你喜欢
    • 2018-09-19
    • 1970-01-01
    • 2017-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多