【问题标题】:how to show related product in Django?如何在 Django 中显示相关产品?
【发布时间】:2021-07-07 08:10:23
【问题描述】:

我有大约 10 多个模型,我将展示其中的 3 个。其中名称为motorsdrumslide。现在在这三个模型中,一个字段是相同的,即名称code

试图解释:

models.py

class Motors(models.Model):
    .
    .
    code = models.CharField(max_length=10)
    .
    .
    .

    def __str__(self):
        return str(self.id)

class Drum(models.Model):
    .
    .
    code = models.CharField(max_length=10)
    .
    .
    .

    def __str__(self):
        return str(self.id)

class Sliders(models.Model):
    .
    .
    code = models.CharField(max_length=10)
    .
    .
    .

    def __str__(self):
        return str(self.id)

现在在上述模型中,它们与code 具有相同的字段。在code 中,它们具有相同的名称,例如:在一个型号中,代码是DD1, DD2, DD3,另一个型号代码是DD1, DD2, DD3

现在在上面,代码是匹配的。因此,如果用户选择一台电机,CodeDD1。然后用代码DD1 显示相关的2 个型号,或者如果用户选择一个带有代码DD1 的鼓。然后在Django中显示相关的两个模型项

我使用了添加到购物车功能,代码放在这里。

views.py

def addProductMotor(request):
    user = request.user
    motor_id = request.GET.get('motor_id')
    motor_cart = Motor.objects.get(id=motor_id)
    Cart(user=user, motor=motor_cart).save()
    return redirect('main:index')

在上面,我在购物车中添加了一个产品项目,然后显示相关项目。怎么可能?

我怎样才能得到这两个相关的模型项?

【问题讨论】:

  • 根据您提供的信息。看起来他们没有关系。必须有 onetoone、manytoone 或 manytomany 字段
  • 我在drum 模型上使用了这个。 motors = models.ManyToManyField(Motor)。现在,转发怎么办?

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


【解决方案1】:

您可以使用以下代码显示其他 2 个模型对象 -

motor_cart = Motor.objects.get(id=motor_id)  # get motor object
code = motor_cart.code                       # get code from the model
drum = Drum.objects.get(code=code)           # get drum from the code
sliders = Sliders.objects.get(code=code)     # get sliders from the code

我建议您使用模型之间的关系,因为您希望它是相关的。您可以根据需要使用一对一多对一多对多

您可以在Django docs 找到更多信息

【讨论】:

  • 我将如何在 HTML 模板中执行??我有motor.html,然后是drum.html。那么如何进行呢?
【解决方案2】:

您可以使用基于列“代码”的内连接来从表中选择数据

【讨论】:

  • 你能举个例子吗?
猜你喜欢
  • 2021-12-30
  • 1970-01-01
  • 2016-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-30
  • 1970-01-01
相关资源
最近更新 更多