具有字段名称值的Django ManyToMany字段

时间:2016-09-07 17:43:49

标签: python django django-models django-forms django-admin

ManyToMany Field Coming as object

model.py

class MedtechProductCategory(models.Model):
name = models.CharField(max_length=128, null=False, blank=False)
type = models.CharField(choices=type_choices_for_tag, max_length=512)

class Meta:
    db_table = 'medtech_product_category'

class ProductsInfo(models.Model):
deal_active = models.BooleanField(default=True)
category = models.ManyToManyField(MedtechProductCategory,  related_name='product_info_category')

class Meta:
    db_table = 'products_info'

def getTags(self):
    return self.category.values_list()

admin.py

class ProductsInfoAdmin(admin.ModelAdmin):
filter_horizontal = ('category',)
admin.site.register(ProductsInfo, ProductsInfoAdmin)

所以我想在过滤搜索中显示类别字段的名称,并希望在保存时将它们保存为对象。

如何自定义它以显示manytomany字段的名称并在保存时保存manytomany字段的对象

1 个答案:

答案 0 :(得分:5)

向模型添加__unicode__方法,该方法将返回您要使用的字符串。

对于python 3,请改用__str__

# on ProductsInfo model
def __str__(self):
    return self.category.name