No Time Dad

A blog about web development written by a busy dad

Django Many To One Use Case

The examples in the post are specific to Django, but the many to one use case is generic for any SQL query regardless of the web framework. This is also true if there isn’t a webframework at all. The concept of many-to-one, many-to-many, or any other variation of a foriegn key relationship applies to SQL in general.

So, the question is what is the Django many to one use case? Well, the answer is that any time you think you need a field in your data represented as an array or list of multiple values then you need a many to one. This relationship is typically a ForeignKey relationship to another table.

from django.db import models

class Article(models.Model):
    title = models.CharField(max_length=200)
    author = models.CharField(max_length=30)

class Tag(models.Model):
    name = models.CharField(max_length=200)
    article = models.ForeignKey(Article, on_delete=models.CASCADE)

One of my favorite examples to illustrate this is the Article and Tag model. This is where a single article can have multiple tags. For example, this article about Django many to one use cases could be tagged with “django”, “many-to-one”, “sql”, etc. When the Article record is queried from the database, it’d be nice to have all of the tags in an array so they can be easily iterated and displayed.

This is exactly what the Django many to one relationship would do for you. Depending on the query, you could get results that look as follows:

{
  "title": "Django Many To One Use Case",
  "author": "notimedad",
  "tags": ["django", "many-to-one", "sql"]
}

A tempting alternative approach would be to not create a second table with a FK relationship and instead represent the tags as a comma separated string on the Article model. This is a bad approach. It’ll almost certainly cause issues, especially if data somehow gets saved in an unexpected format. Plus, you’ll have to split the value and do some other manual checks to ensure the data is valid. It’s more work up front, but creating the second table with a foreign key relationship is almost always a better approach.

from django.db import models

class Article(models.Model):
    title = models.CharField(max_length=200)
    author = models.CharField(max_length=30)
    # This is a bad idea...
    tags = models.CharField(max_legnth=250)

Not to say that I haven’t done the “string array” approach mentioned above…because I definitely have. But I wasn’t proud of it, and I’m sure I was in a rush or working with some legacy code base. Try not to judge me.

Related posts