user2453911
user2453911

Reputation: 57

How to create a database table based off a list

I am using Flask/Django to create my database model so I understand Python code but SQL is fine as well.

I was wondering how I can create a database filled with options from a list in that database and I was hoping someone could point me in the right direction or give me an example.

This is going to be a REST API and I want the data to be returned in JSON as well as use curl to test it.

E.g. What I want the tables to look like

Food:
Apples
Oranges
Pears
Sugar

Recipe:
Description: Baked Pears (can be changed by user)
Needs: Pears, Sugar
(User can only choose from the Food list)

User sends request to the API to create a new recipe. It calls the list of food options and the Javascript client lists those options to choose from. Then the user posts his recipe to the database. I am lost how to have the database relate the Food items to the created Recipes.

Upvotes: 0

Views: 88

Answers (1)

Alexander
Alexander

Reputation: 871

Sounds like you would need to use Django's many to many relationship. In your example, the Recipe would contain a many to many relationship to the Food.

from django.db import models

class Food(models.Model):
    name = models.CharField(max_length=30)

    def __str__(self):
        return self.name

class Recipe(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField()
    ingredients = models.ManyToManyField(Food)

    def __str__(self):
        return self.title

Django 1.7 Docs: many_to_many

Upvotes: 1

Related Questions