0

I am completely new to Django, so forgive me if this is the wrong approach. While I'm trying to learn Django, I like to do my own little practice problems to solidify my understanding.

Working with models I created the example model objects:

from django.db import models


class Food(models.Model):
    name = models.CharField(
        max_length=50,
        help_text="Name of Fruit or Vegetable"
    )
    food_group = models.CharField(
        max_length=9,


class Vitamins(models.Model):
    name = models.ForeignKey(
        Food,
        on_delete=models.CASCADE
    )
    vitamin_A = models.CharField(
        max_length=20,
    )
    .
    .
    .
    folate = models.CharField(
        max_length=20,
        help_text="Folic Acid"
    )

In my object, I have 5 identical fields that store text i.e. (Trace amounts, 5mg, No Information). However it seems tedious to type out every field. Is there a more efficient way to do this?

1
  • Why don't you create a new record for each entry of Vitamin? I mean a Vitamin model with food (FK), name and folate? And while creating a entry you just create a new record. Commented Jun 8, 2021 at 14:47

1 Answer 1

2

I think you should take advantage of the relational database and create a model for Vitamin, with name and folate, something like this

from django.db import models


class Food(models.Model):
    name = models.CharField(
        max_length=50,
        help_text="Name of Fruit or Vegetable"
    )


class Vitamin(models.Model):
    food = models.ForeignKey(
        Food,
        on_delete=models.CASCADE
    )
    name = models.CharField(
        max_length=20,
    )
    folate = models.CharField(
        max_length=20,
        help_text="Folic Acid"
    )

And then for every Vitamin in the Food you create a record. It can be 1, 2 or N. This is very flexible and scaleable.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I accepted the answer. I realize that I am stuck in a mindset where I am trying to force a spreadsheet into my models. I think every column in a spreadsheet needs it own field within an object. Instead of just thinking about creating a record of what I need and relating it to my object, which is much more flexible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.