【问题标题】:How to query ManyToManyField to get the attribute from another model如何查询 ManyToManyField 以从另一个模型中获取属性
【发布时间】:2021-03-08 11:55:19
【问题描述】:

这是我的 Model_Items:

class Model_Items(models.Model):
    title = models.CharField(max_length=20, default='')
    manufacturer = models.CharField(max_length=10, default='')
    make = models.CharField(max_length=20, default='')
    model = models.CharField(max_length=20, default='')
    sku = models.CharField(max_length=10, default='')

Po 与哪个具有多对多关系:

class Po(models.Model):
    po_number = models.CharField(max_length=10, default='')
    receive_date = models.DateField(auto_now=False, auto_now_add=False, default='')
    model_item = models.ManyToManyField(Model_Items)
    site_code = models.CharField(max_length=10, default='')
    comment = models.TextField(max_length=50, default='')

现在在我看来,我查询它:

def po_page(request, *args, **kwargs):
    po = Po.objects.all()

    context = {
        'po_list': po,
    }
    return render(request, 'po/po_page.html', context)

在我的模板上:

{% for my_po_list in po_list %}
    <div class="card">
        <table class="table table-bordered" >
            <tr>
                <td class="col-md-2">{{ my_po_list.po_number }}</td>
                <td class="col-md-2">{{ my_po_list.receive_date }}</td>
                <td class="col-md-2">{{ my_po_list.model_item.all }}</td>
                <td class="col-md-2">{{ my_po_list.site_code }}</td>
                <td class="col-md-2">{{ my_po_list.comment }}</td>
                <td class="col-md-2">{{ model }}</td>
            </tr>
        </table>
    </div>
{% endfor %}

我一直在努力从 Model_Items 类中获取标题并显示它。
但是符合:

{{ my_po_list.model_item.all }}

改为显示以下内容 &lt;QuerySet [&lt;Model_Items: Mac 16 Dev&gt;, &lt;Model_Items: Mac 13 Std&gt;]&gt;.

我知道该行应该这样做,但我如何过滤它以便只显示 Model_Items 标题。

【问题讨论】:

    标签: python database sqlite django-models


    【解决方案1】:

    我建议使用 for 循环来遍历模型项。我还添加了在标题之间添加逗号的方法。

    <td class="col-md-2">
        {% for model_item in my_po_list.model_item.all %}
            {{model_item. title}}{% if not forloop.last %}, {% endif %}
        {% endfor %}
    </td>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-28
      • 1970-01-01
      相关资源
      最近更新 更多