一对多模型和Django Admin

时间:2016-04-04 08:13:46

标签: python django

我有以下型号:

#models.py

class Section(models.Model):
    name = models.CharField(max_length=20)


class Tags(models.Model):
    parent = models.ForeignKey(Section)
    name = models.CharField(max_length=255, blank=True)

class Article(TimeStampedMode):
    ...
    tag = models.ForeignKey(Tags)

在Django管理员中,tag显示为HTML <select multiple> 我想做的是:
Section可以有多个TagsArticle我可以从Tags中选择Section。 此外,它需要能够获得Article的{​​{1}}(通过Section?)。

目前这有效。但是,tags.parent代替<select multiple>而不是Tags而不是<input>。 我想要的是<select multiple>Tags都显示为Section

编辑:

我想要的是: screenshot

2 个答案:

答案 0 :(得分:1)

By using a foreign key to define the relationship, you're limiting the number of Tags an Article may have to 1. For an Article to have more than one Tag, you'll want to use a ManyToMany relationship.

Read more on many-to-many relationships with Django here: https://docs.djangoproject.com/en/dev/topics/db/examples/many_to_many/

The Django admin site will automatically use a select if you're using a foreign key relationship, or a multi-select if you're using a many-to-many relationship.

Here's what a many-to-many will look like from Article to Tags:

class Article(TimeStampedMode):
    ...
    tag = models.ManyToManyField(Tags)

答案 1 :(得分:0)

我不能正确理解你的需要。但根据您的图片,您需要在Section Tags设置One-To-Many field Article

#models.py

class Section(models.Model):
    name = models.CharField(max_length=20)

class TagName(models.Model):
     tag_name = models.CharField(max_length=255, blank=True)

class Tags(models.Model):
    parent = models.ForeignKey(Section)
    name = models.ForeignKey(TagName)

class Article(TimeStampedMode):
    ...
    tag = models.ForeignKey(Tags)

我认为这种方法更有用,可以满足您的需求。

给定型号代码的屏幕截图:

this is Article page

go into tag and you can see select multiple for both fields

谢谢