0

I'm making an app atm where I get dummy data from a json file. My filed in this file looks like this:

 {
  "model": "card.model",
  "pk": 2222,
  "fields": {
    "meal_1": 5555,
    "meal_2": 5556,
    "meals": "[5555, 5556]"
  }
}

{
  "model": "meal.model",
  "pk": 5555,
  "fields": {
    "name": "Pizza",
    "vagan": True
  }
}

{
  "model": "meal.model",
  "pk": 5556,
  "fields": {
    "name": "Sandwich",
    "vagan": False
  }
}

I have a Meal class that contains: name, photo, description. I have also Card class that gets info right from json file.

class Card() {
  meal_1 = models.ForeignKey(
    Meal,
    related_name='meal_1"
  )
   meal_2 = models.ForeignKey(
    Meal,
    related_name='meal_2"
  )
  
  meals=[] ??
}

How can I add an array field that will contain a reference to these meals. What I want to achieve is loop over this meals and place into django template. Now I do this by reference to each filed: instance.meal_1.name... etc.

2 Answers 2

1

I think you could add Card as ForeignKey to your Meal class. Then in the template, you can loop for each Meal in the Card.

meal.py

class Meal(models.Model):
    ...
    card = models.ForeignKey(Card, on_delete=models.CASCADE)
    ...
    ...

template.html

{% for meal in card.meal_set %}
   {{ meal.name }}
{% endfor %}
Sign up to request clarification or add additional context in comments.

Comments

0

I think Night Owl's approach is pretty good, but there is also another approach you can take. That is using ManyToManyField.

In the given JSON, id of meal_1 and meal_2 are inside meals field. So I don't think its necessary for you to consider meal_1 and meal_2 when creating models(because there could be more than 2 meals). So you can try to create ManyToMany Relation between Card and Meal. Like this:

class Meal(models.Model):
    name = models.CharField(max_length=255)
    vagan = models.BooleanField()

class Card(models.Model):
    meals = models.ManyToManyField(Meal)


# usage

   meal = Meal.objects.create(name="sandwitch", vegan=False)
   card = Card.objects.create()
   card.meals.add(meal)

# template

   {% for meal in card.meals.all %}
       {{ meal.name }}
       {{ meal.vegan }}
   {% endfor %}

Comments

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.