我有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}"
答案 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 }}。