Home > Software engineering >  How to apply two models to one view?
How to apply two models to one view?

Time:11-04

I have 2 models Goods and Number models and I need to apply those models to IndexView. I would be pleased to know how this can be done in my code sorry for english. this is code of views.py

from django.views import generic
from django.utils import timezone
from .models import Question
from .models import Goods
from .models import Number

class IndexView(generic.ListView):
    template_name = 'Homepage/index.html'
    model = Goods
    context_object_name = 'goods'

    def description(self):
        return self.description_text

    def price(self):
        return self.price_text

class NumbersView(generic.ListView):
    template_name = 'Homepage/index.html'
    model = Number
    context_object_name = 'numbers'

    def number1(self):
        return self.number1_text

    def number2(self):
        return self.number2_text

this is code of models.py

    class Goods(models.Model):
    description_text = models.CharField(max_length=200)
    price_text = models.CharField(max_length=200)
    image_sale = models.ImageField()

    def __str__(self):
        return self.image_sale

    def __str__(self):
        return self.description_text

    def __str__(self):
        return self.price_text


    class Number(models.Model):
        number1_text = models.CharField(max_length=200)
        number2_text = models.CharField(max_length=200)

    def __str__(self):
        return self.number1_text

    def __str__(self):
        return self.number2_text

CodePudding user response:

class IndexView(generic.ListView):
    template_name = 'Homepage/index.html'
    model = Goods
    context_object_name = 'goods'

    def description(self):
        return self.description_text

    def price(self):
        return self.price_text

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        numbers = Number.objects.all()
        context['numbers'] = numbers
        return context
  • Related