Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Django models !!! Many foreignKeys

Hi everybody, i made two models, "Salad" and "Ingredients"....also i want to add ingredientslist parameter that contains different ingredients from "Ingredients" model depending on Salad like a list of ForeignKeys .... and i don't know what to write after ingredientlist = models.

models.py

from django.db import models

class Salad(models,Model):
    name = models.CharField(max_length = 255)
    ingredientlists = models.

class Ingredients(models):
    name = models.Charfield(max_length = 255)

    def __str__(self):
        return self.name

salad.html

{% block content %}
{{salad.name}}
{% for ingredient in ingredientslist %}
{{ingredient}}
{% endfor %}
{% endblock %}

1 Answer

Hello,

you need a ManyToManyField.

ingredients = models.ManyToManyField(Ingredient)

if salad is a Salad object, you can get to its ingredients with

salad.ingredients.all()

also if ingredient is an Ingredient object you can get to all the salads it is used in with

ingredient.salad_set.all()

Here is a link to the relevant page in the documentation

https://docs.djangoproject.com/en/1.10/topics/db/examples/many_to_many/

it works, thanks