ManyToMany字段尽管有值但仍返回None

时间:2019-06-22 20:37:20

标签: python django

我有2个班级:类别和比萨饼。其中一个是对象的类别列表,另一个是对象。问题是,当我调用一个对象时,我可以看到所有字段,除了ManyToMany字段返回LC_*而不是分配的值。

这是我的模型。py:

catalog.Category.None

这是我的shell输出:

class Category(models.Model):
    CLASSIC = 'Classic'
    VEGETARIAN = 'Vegetarian'
    SPICY = 'Spicy'
    TYPE = [
        (CLASSIC, 'Classic'),
        (VEGETARIAN, 'Vegetarian'),
        (SPICY, 'Spicy')
    ]

    type = models.CharField(
        max_length=100,
        choices=TYPE
    )

    def __str__(self):
        return self.type

    class Meta:
        verbose_name_plural = 'Categories'


class Pizza(models.Model):
    name = models.CharField(max_length=100)
    price = models.IntegerField()
    size = models.OneToOneField(
        Size,
        on_delete=models.CASCADE,
        primary_key=True
    )
    category = models.ManyToManyField(Category)

    def __str__(self):
        return f"name = {self.name}, size = {self.size}, category = {self.category}"

1 个答案:

答案 0 :(得分:0)

import json from pprint import pprint json_file = "/some/path/to/json/file" with open(json_file) as json_data: data = json.load(json_data) json_data.close() for i in data: event_key_b = event.get('b') for x in i: event_key_2 = event.get('key_2') x = {'b' : something_b, 'key_2' : value_2} print(x) 实际上将返回some_pizza.category,因为它是catalog.Category.None,并且是ManyRelatedManager在此类str(..)上的预期输出。您应该添加ManyRelatedManager才能将其呈现为.all()的列表:

Category
  

注意:由于class Pizza(models.Model): # ... def __str__(self): return f"name = {self.name}, size = {self.size}, category = {self.category.all()}"可以具有零个,一个或多个类别,因此最好将Pizza ManyToManyField命名为{{1 }}。