Django详细视图:在详细视图中从另一个模型检索数据

时间:2020-08-18 03:41:24

标签: python django django-models django-views django-templates

我试图显示与给定“项目”相关的“ cliqueclasses”列表,但只是无法正确获取循环模板。我也想更进一步,只附加与该项目相关的类(基于外键)

我已经尝试了一段时间,到目前为止还没有碰到任何运气,尤其是在模板方面!

Models.py

class Item(models.Model):
    title = models.CharField(max_length=100)
    price = models.FloatField()
    discount_price = models.FloatField(blank=True, null=True)
    category = models.CharField(choices=CATEGORY_CHOICES, max_length=2)
    label = models.CharField(choices=LABEL_CHOICES, max_length=1)
    slug = models.SlugField()
    description = models.TextField()
    image = models.ImageField()

    def save(self, *args, **kwargs):
    ...

    def __str__(self):
        return self.title
    ...

class CliqueClass(models.Model):
    title = models.CharField(max_length=100)
    start_date = models.DateTimeField(auto_now_add=True)
    end_date = models.DateTimeField(auto_now_add=True)
    item = models.ForeignKey(Item, related_name='items',
                             on_delete=models.CASCADE)
    description = models.TextField()
    plan = models.TextField()
    slug = models.SlugField()
    image = models.ImageField()

    def save(self, *args, **kwargs):
    ...

    def __str__(self):
    ...

我的Views.py

class ItemDetailView(DetailView):
    model = Item
    template_name = "clique.html"
    # queryset = CliqueClass.objects.filter(title=Item.title)

    def get_context_data(self, **kwargs):
        """
        This has been overridden to add `cliqueclass` to the template context,
        now you can use {{ cliqueclass }} within the template
        """
        context = super().get_context_data(**kwargs)
        context['cliqueclass'] = CliqueClass.objects.all()
        return context

我的网址是.py

path('clique/<slug>/', ItemDetailView.as_view(), name='clique'),

我的clique.html模板:

 {% for class in object.cliqueclass_set.all %}
  <!--Look through all cliques classes-->
  <div class="mb-3">
    <a href="">
      <span>{{ class }}</span>
      <span class="badge purple mr-1">{{ class.title }}</span>

      <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Natus suscipit modi sapiente illo soluta odit
        voluptates,
        quibusdam officia. Neque quibusdam quas a quis porro? Molestias illo neque eum in laborum.</p>

    </a>
  </div>

  <hr class="solid">
  {% endfor %}

任何帮助将不胜感激:)

1 个答案:

答案 0 :(得分:1)

首先,您需要更改FK的 related_name

class CliqueClass(models.Model):
    # rest of your code
    item = models.ForeignKey(Item, related_name='clique_classes',
                             on_delete=models.CASCADE)

related_name可以是任意名称,但是,我认为clique_classes是更合适的名称。

如果您不熟悉related_name,请阅读更多

  1. What is related_name in Django -- (SO Post)

  2. Following backwards relationship -- (Django doc)

  3. ForeignKey.related_name -- (Django doc)

更改related_name后,您需要通过执行以下命令来迁移数据库,

  1. python manage.py makemigrations
  2. python manage.py migrate

然后,在您看来,删除 get_context_data(...) 方法,因为它与此特定问题无关。

class ItemDetailView(DetailView):
    model = Item
    template_name = "clique.html"

然后,将模板代码更改为

{% for clique_class in object.clique_classes.all %}
    {{ clique_class.title }}
{% endfor %}