【问题标题】:Django ManyToMany Field with field name values具有字段名称值的 Django ManyToMany 字段
【发布时间】:2017-01-15 12:27:27
【问题描述】:

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 字段的对象

【问题讨论】:

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


    【解决方案1】:

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

    对于 python 3,请改用__str__。

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

    【讨论】:

    • 哪个型号 MedtechProductCategory 或 ProductsInfo 以及应该添加什么到 filter_horizo​​ntal ?
    • @Gagan 在您制作的每个模型上都包含__str__ 或__unicode__ 方法是一种很好的做法。上面的示例应该继续使用ProductsInfo 模型。我不明白你的其余问题。
    猜你喜欢
    • 2017-04-06
    • 1970-01-01
    • 2020-02-18
    • 1970-01-01
    • 2014-05-27
    • 2017-04-08
    • 1970-01-01
    • 2020-12-08
    • 1970-01-01
    相关资源
    最近更新 更多