简体   繁体   English

如何在 Django 模型中添加基于数组的文件

[英]How to add an array based filed in django model

I'm making an app atm where I get dummy data from a json file.我正在制作一个应用程序 atm,我从 json 文件中获取虚拟数据。 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.我有一个 Meal 类,其中包含:名称、照片、描述。 I have also Card class that gets info right from json file.我还有 Card 类,可以直接从 json 文件中获取信息。

 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.我想要实现的是循环这顿饭并放入 django 模板中。 Now I do this by reference to each filed: instance.meal_1.name... etc.现在我通过参考每个文件来做到这一点:instance.meal_1.name...等。

I think you could add Card as ForeignKey to your Meal class.我认为您可以将 Card 作为 ForeignKey 添加到您的 Meal 课程中。 Then in the template, you can loop for each Meal in the Card.然后在模板中,您可以为卡片中的每顿饭循环。

meal.py膳食.py

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

template.html模板.html

{% for meal in card.meal_set %}
   {{ meal.name }}
{% endfor %}

I think Night Owl's approach is pretty good, but there is also another approach you can take.我认为 Night Owl 的方法非常好,但您还可以采用另一种方法。 That is using ManyToManyField .那就是使用ManyToManyField

In the given JSON , id of meal_1 and meal_2 are inside meals field.在给定的JSONmeal_1meal_2 id 在meals字段内。 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).所以我认为你在创建模型时没有必要考虑meal_1meal_2 (因为可能有超过 2 顿饭)。 So you can try to create ManyToMany Relation between Card and Meal .所以你可以尝试在CardMeal之间创建 ManyToMany Relation 。 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 %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM