2

In 5th grade when we learned how to outline a research paper, our teacher taught us that you should never have a single bullet point. I feel like I am breaking this rule, and there might be a better way.

I have model, Movie, which has fields like title and year. I want to also include genre. However, movies can fall into more than one genre. So I feel like I need to have a many-to-many relationship. But I don't really want to make Genre it's own model class, because there would only be one field, Genre.genre. It seems wrong to me. I know I could have genre be a CharField and separate genres with some sort of a separator sentinel, ie action|adventure|comedy. But is that the best way to do it?

I am planning to run raw SQL queries against this database, so simplicity is of high value right now.

Chase Roberts
  • 9,082
  • 13
  • 73
  • 131
  • Try https://pypi.python.org/pypi/django-multiselectfield/ or https://pypi.python.org/pypi/django-select-multiple-field/ . With this,you don't need to separate the choices by comma as genre choice strings may contain commas themselves. – Prakhar Trivedi Dec 07 '16 at 13:10

2 Answers2

2

There is no such general rule of quality regarding models with a single attribute. As movies can have more than one genre and genres obviously can belong to more than one movie, a ManyToMany relationship might be your best shot here.

One alternative would be to have a genres TextField in your model, and simply save all the genres as a comma separated list. Among many obvious problems of this approach are the fact that you wouldn't be able to efficiently query movies by genre and there would be no guarantee that the same genre wouldn't be written differently in two different movie instances.

If you are using PostgreSQL, another option is to define genres as an ArrayList of CharFields. Define a constant with every possible genre and pass it to your CharField's choices.

COMEDY = 'COMEDY'
ADVENTURE = 'ADVENTURE'
ACTION = 'ACTION'
# ...

GENRE_CHOICES = (
    (COMEDY, 'Comedy'),
    (ADVENTURE, 'Adventure'),
    (ACTION, 'Action'),
    # ...
)
lucasnadalutti
  • 5,818
  • 1
  • 28
  • 48
0

AFAIK there is no such rule. It makes sense for the genre to be a separate model. So querying all genre and accessing the movies fall in that genre would be more straight forward.

If you are still feeling weird, put a created_time and created_user field in the Genre model. You will find it useful later.

Rag Sagar
  • 2,314
  • 1
  • 18
  • 21