尝试在管理页面中以逗号分隔的列表函数返回manytomanyfield的表名。
class Machine(models.Model):
class Meta:
verbose_name = 'Machine'
verbose_name_plural = '02 Machines'
machine_type_choices = (...)
valuestream = models.ForeignKey(Valuestream, on_delete=models.CASCADE)
machine_number = models.CharField(
max_length=6,
help_text="Please exclude the 'm' in the machine number",
unique=True,
validators=[
MinLengthValidator(4, message="Machine numbers have to be greater than 3 digits long"),
]
)
machine_type = models.CharField(max_length=50, choices=machine_type_choices)
machine_brand = models.CharField(max_length=30, blank=True)
pub_date = models.DateTimeField(auto_now=True)
pass
def __str__(self):
return str(self.machine_number)
class SWS_Document(models.Model):
class Meta:
verbose_name = 'SWS Document'
verbose_name_plural = '03 SWS Documents'
machines = models.ManyToManyField(Machine, related_name='SWS_documents')
document_description = models.CharField(max_length=150, default="")
pub_date = models.DateTimeField(auto_now=True)
def __str__(self):
return str(self.machines.machine)
我无法弄清代码的最后一点。我试图返回与SWS_Document关联的列表中的所有相关机器。
答案 0 :(得分:0)
您不应该在模型str
方法中真正执行此操作,因为当您想要模型的字符串表示形式时,该方法将覆盖所有时间。在管理方法中执行此操作,然后将该方法的名称添加到list_display
属性中。
class SWSDocumentAdmin(admin.ModelAdmin):
model = SWS_Document
list_display = ('machine_list',)
def machine_list(self, obj):
return ', '.join(obj.machines.values_list('machine_number', flat=True))