[Fixed]-One-To-Many models and Django Admin

0👍

I don’t understand your need correctly. But according to your image, you need Section and Tags are set One-To-Many field in 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)

I think this method is more useful and matching with your need.

screenshot of the given model code:

this is Article page

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

Thank you

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)

Leave a comment