我有一个Django项目,包含以下模型:
class Ingredient(models.Model):
drink = models.ForeignKey(DrinkRecipe, on_delete=models.CASCADE)
ingredient_rhum = models.ForeignKey(Bottle, on_delete=models.CASCADE, null=True, blank=True)
ingredient_name = models.CharField(max_length=255, blank=True)
ingredient_amount = models.DecimalField(decimal_places=1,max_digits=5, validators=[MinValueValidator(0.01)])
def __str__(self):
if self.ingredient_rhum:
return self.ingredient_rhum
return self.ingredient_name
def get_absolute_url(self):
return self.drink.get_absolute_url()
以及:
class Bottle(models.Model):
bottle_name = models.CharField(max_length=255, blank=False, verbose_name='Name')
bottle_slug = models.SlugField(unique=True, blank=True, null=True)
bottle_info = HTMLField(blank=False, verbose_name='Information about the bottle')
bottle_tastingnotes_text = HTMLField(verbose_name='Tasting description', blank=False)
bottle_tasting_notes = HTMLField(verbose_name='Tasting notes', blank=False)
bottle_tastingnotes_finish = HTMLField(verbose_name='Finish',blank=False)
bottle_image = models.ImageField(upload_to=image_upload_handler)
sorting_number = models.IntegerField()
bottle_abv = models.DecimalField(max_digits=3,decimal_places=1, verbose_name='ABV', validators=[MinValueValidator(0.01)])
img_location = 'bottles'
def __str__(self):
return self.bottle_name
class Meta:
ordering = ['sorting_number', 'bottle_name']
def get_bottle_link(self):
return reverse('rhumSite:drinkBottle',kwargs={'tag':self.bottle_name} )
def get_edit_link(self):
return reverse('rhumSite:edit_bottle',kwargs={'id':self.id})
def save(self, *args, **kwargs):
abv = str(self.bottle_abv)
if not self.id:
# Newly created object, so set slug
self.bottle_slug = slugify(self.bottle_name + abv)
super(Bottle, self).save(*args, **kwargs)
当我在CreateView中使用inline-modelset-factory时,一切都很好。但是:当我尝试在Admin中添加成分或尝试删除成分或其他具有Bottle
模型ForeignKey的对象时,我会收到以下错误:__str__ returned non-string (type Bottle)
我做错了什么,我该如何修复它?
2条答案
按热度按时间oknwwptz1#
你返回
ingredient_rhum
,这是一个Bottle
,而不是一个str
ing,__str__
应该返回一个字符串。您可以将Bottle
转换为字符串:uidvcgyl2#
使用
str()
类来转换它。