ManyToMany 字段 returns None 而不是给我数据

ManyToMany field returns None instead of giving me the data

我正在用 Django 开发餐厅管理应用程序。当我尝试打印客户订购的商品时,我得到

testapp.Menu.None testapp.Menu.None

只有那么多字段显示 none。其他都正常。

这些是我的模型:

categories=(
    ('Starters','Starters'),
    ('Maincourse','Maincourse'),
    ('Breakfast','Breakfast'),
    ('Desserts','Desserts'),
    ('Beverages','Beverages')
)
class Menu(models.Model):

    name=models.CharField(max_length=200,null=True)
    category=models.CharField(max_length=200,null=True,choices=categories)
    price=models.IntegerField(null=True)
    date_created=models.DateTimeField(auto_now_add=True,null=True)

    def __str__(self):
        return self.name

class Customer(models.Model):

    name=models.CharField(max_length=200)
    email=models.CharField(max_length=200)
    phone=models.IntegerField()
    address=models.TextField(max_length=200)
    date_created=models.DateTimeField(auto_now_add=True,null=True)

    def __str__(self):
        return self.name

class Orders(models.Model):
    status=(
        ('Out of delivery','Out of delivery'),
        ('Pending','Pending'),
        ('Order recieved','Order recieved'),
    )
    customer=models.ForeignKey(Customer,null=True,on_delete=models.SET_NULL)
    items=models.ManyToManyField(Menu)
    status=models.CharField(max_length=200,choices=status)
    date_created=models.DateTimeField(auto_now_add=True,null=True)

这是我的 view.py 文件

def customer_info(request,pk):
    customer=Customer.objects.get(id=pk)
    order=customer.orders_set.all()
    
    context={
        'customer':customer,
        'order':order

    }
    return render(request,'customer_info.html',context)

我的html文件

<table>
        <tr>
            {{customer.name}}
            <br>
            {% for order in order %}
            {{ order.items }}
            {% endfor %}
        </tr>
    </table>

请帮我解决这个问题。

{% for order in order %} 将无法正常工作。

改变你的看法:

def customer_info(request,pk):
    customer = Customer.objects.get(id=pk)
    orders = customer.orders_set.all()
    
    context={
        'customer': customer,
        'orders': orders
    }
    return render(request,'customer_info.html',context)

还有你的模板:

<table>
    <tr>
        <td>Name: {{customer.name}}</td>
        <td>
            Orders:
            {% for order in orders %}
                {{ order.items.all }}
            {% endfor %}
        </td>
    </tr>
</table>