繁体   English   中英

Django遍历具有unique_together并且没有pk的对象集

[英]Django Iterating through an object set with unique_together and no pk

我试图遍历传递给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,因此我无法为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'")

查看回溯电话

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

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

从文档:

如果您想指定自定义主键,只需在其中一个字段上指定primary_key = True即可。 如果Django看到您已显式设置Field.primary_key,则不会添加自动ID列。

所以,你已经覆盖了content.idcontent.content_id

您不再具有id字段,因为您已将primary_key=Truecontent_id字段。

尝试将id替换为content_id 就像是:

{{ content.content_id }}

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

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

您可以检查: Django模型(1054,““字段列表”中的未知列”)

另外: “字段列表”中的未知列“”。 Django的

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM