Django-Textchoices和admin.site.register [英] Django - Textchoices and admin.site.register

查看:43
本文介绍了Django-Textchoices和admin.site.register的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个选择类TextChoices:

I have a choice class TextChoices:

class Category(models.TextChoices):
    vegetable = 'VEG', 'vegetable'
    fruit = 'FRT', 'fruit'
    carbs = 'CRB', 'carbs'
    fish = 'FSH', 'fish'
    meat = 'MT', 'meat'
    sweet = 'SWT', 'sweet'
    dairy = 'DRY', 'dairy'
    ready = 'RDY', 'ready'

    # def __str__(self):
    #     return self.name
    def __str__(self):
        return self.choices

用于:

class Fooditem(models.Model):

    name = models.CharField(max_length=200)
    #    category = models.ManyToManyField(Category)
    category = models.CharField(max_length=3, choices=Category.choices, default=Category.vegetable)

现在,我想使类别可以由管理员

Now, I would like to make Category editable by admin:

admin.site.register(Category)

但是我有以下错误:

  File "PycharmProjects\Calories_New\Fityfeed\admin.py", line 14, in <module>
    admin.site.register(Category)
  File "PycharmProjects\Calories_New\venv\lib\site-packages\django\contrib\admin\sites.py", line 106, in register
    if model._meta.abstract:
AttributeError: 'Category' object has no attribute '_meta'

我在Django中相对较新,很感谢您的帮助,也帮助您理解我如何自己解决这些问题(在参考文档中苦苦挣扎)

I am relatively new in Django and would appreciate your help, also in understanding how I can solve these problems myself (struggling with reference documentation)

非常感谢!D

推荐答案

由于可以动态添加类别,因此应为 Model :

Since categories can be added dynamically it should be a Model:

class Category(models.Model):
    name = models.CharField(max_length=35)

接下来要在 Category Fooditem 之间建立关系,您要使用

Next to make the relationship between Category and Fooditem you want to use a ForeignKey [Django docs]:

class Fooditem(models.Model):
    name = models.CharField(max_length=200)
    category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="food_items")

要访问食品类别:

print(food_item_instance.category.name) # Outputs "vegetable" or whatever the category is.

还可以将每个食品归为一个类别:

Also to get each food item in a category:

food_items = category_instance.food_items.all()

由于它是模型,现在您可以将 Category 注册到管理站点.

Now you can register Category to the admin site since it is a model.

这篇关于Django-Textchoices和admin.site.register的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆