【问题标题】:How to setup categories model efficiently in python如何在python中有效地设置类别模型
【发布时间】:2019-05-16 11:39:13
【问题描述】:

我正在 Django 中建立一个模型。有一个名为 category 的字段,我创建了一个外部字段(因为它将包含许多将通过模型添加的类别)。

我希望能够为用户或管理员创建的每个配置文件添加多个类别,但我只能为每个创建的配置文件添加一个类别。

请问我该如何解决这个问题,我不知道如何解决这个问题。

到目前为止,下面的代码显示了我到目前为止能够做到的程度,以及我的管理员的图片:

from django.conf import settings

from django.db import models

class Category(models.Model):
    name                    = models.CharField(max_length=50, default=None)
    slug                    = models.SlugField(max_length=50, unique=True, default=None)

    class Meta:
        ordering = ('name',)
        verbose_name = 'category'
        verbose_name_plural = 'categories'

    def __str__(self):
        return self.name

class Profile(models.Model):
    bio                     = models.TextField(blank=False)
    personal_website_url    = models.URLField(blank=True)
    personal_website_name   = models.URLField(blank=True)

    general_category        = models.ForeignKey(Category, on_delete=models.CASCADE)


    def __str__(self):
        return self.bio or ""

如何为每个配置文件添加多个类别?因为我只能在 Django 模型中为每个配置文件添加一个类别。

【问题讨论】:

  • 您确定想要ManyToManyField?

标签: python django django-models django-rest-framework


【解决方案1】:

您只能将单个对象保存到ForeignKey 字段。如果您想将多个类别添加到单个配置文件,请使用多对多字段。

   general_category = models.ManyToManyField(Category, on_delete=models.CASCADE)

【讨论】:

  • 非常感谢您的回答,它确实对我有用。我很感激
猜你喜欢
  • 1970-01-01
  • 2020-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-12
相关资源
最近更新 更多