我有以下型号:
#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
可以有多个Tags
,Article
我可以从Tags
中选择Section
。
此外,它需要能够获得Article
的{{1}}(通过Section
?)。
目前这有效。但是,tags.parent
代替<select multiple>
而不是Tags
而不是<input>
。
我想要的是<select multiple>
和Tags
都显示为Section
。
编辑:
答案 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)
我认为这种方法更有用,可以满足您的需求。
给定型号代码的屏幕截图:
go into tag and you can see select multiple for both fields
谢谢