我正在尝试让Django模型自动为自身构建一个典型的__str __(self)值(在模型定义中),但是基于3个ManyToMany字段。与使用基本字段类型(如前两个模型中)不同,这似乎不适用于M2M字段(请参阅第三个模型)。 模型迁移得很好,但在管理员中引用时会导致错误。
非常感谢任何帮助,谢谢!
class Party(models.Model):
name=models.CharField("Party", max_length=150)
def __str__(self): # __unicode__ on Python 2
return self.name
class Meta:
ordering = ('name',)
class ValCharBehav(models.Model):
name=models.CharField("Value / Character / Behaviour", max_length=150, unique=True)
def __str__(self): # __unicode__ on Python 2
return self.name
class ValCharBehavWithPeople(models.Model):
vcb=models.ManyToManyField(ValCharBehav, verbose_name="Value / Character / Behvaiour")
bywhom=models.ManyToManyField(Party, verbose_name="By Whom", blank=True, related_name="valCharByWhomReverseAccessor")
towhom=models.ManyToManyField(Party, verbose_name="To Whom", blank=True, related_name="valCharToWhomReverseAccessor")
def __str__(self): # __unicode__ on Python 2
return self.vcb.name+": by: "+self.bywhom.name+", to: "+self.towhom.name
答案 0 :(得分:0)
def get_vcb_name(self):
return ' | '.join(self.vcb.filter(
name__isnull=False
).values_list('name', flat=True))
def get_bywhom_name(self):
return ' | '.join(self.bywhom.filter(
name__isnull=False
).values_list('name', flat=True))
def get_towhom_name(self):
return ' | '.join(self.towhom.filter(
name__isnull=False
).values_list('name', flat=True))
def __str__(self):
return self.get_vcb_name()+": by: "+self.get_bywhom_name()+", to: "+self.get_towhom_name()
答案 1 :(得分:0)
或者如果您更喜欢@ ykh的答案稍微简洁一点:
def __str__(self):
return '%s, by %s, to %s' % [
' | '.join(x.values_list('name', flat=True))
for x in (self.vcb, self.bywhom, self.towhom) ]