esfy
esfy

Reputation: 683

One-To-Many models and Django Admin

I have the following models:

#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)

In Django admin, tag shows up as a HTML <select multiple>.
What I'm trying to do is:
A Section could have many Tags, and from Article I could pick a Tags from Section.
Also, it needs to be able to get a Article's Section(via tags.parent?).

Currently this works. But, instead of <select multiple>, Tags shows up as a <input> instead of a <select multiple>. What I want is for both Tags and Section appear as <select multiple>.

edit:

What I want is: screenshot

Upvotes: 0

Views: 1773

Answers (2)

Arun V Jose
Arun V Jose

Reputation: 3379

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

Upvotes: 0

Curtis Olson
Curtis Olson

Reputation: 967

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)

Upvotes: 1

Related Questions