具有嵌套ForeignKey模型的Django QuerySet

时间:2016-08-19 09:04:21

标签: django django-views django-queryset

我有两个型号,一个是产品,一个是Shop。人们将注册一个在线商店并上传他们的产品。现在我需要在我的视图中创建上下文时获取该商店中的产品列表。以下是代码:

class Shop(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, null=False, blank=False)
    products = models.ManyToManyField(Product)
    name = models.CharField(max_length=120, help_text="Enter a Name for your Shop")
    description = models.TextField(null=False, blank=False, help_text="Introduce your Shop in 200 words")
    shop_owner_name = models.CharField(max_length=30, null=False, blank=False, help_text='Enter name of the Owner of Shop.')
    shop_logo = models.ImageField(upload_to=image_upload_to_shop, null=True)
    shop_city = models.CharField(max_length=30, help_text="Enter name of City Where your Shop is located.")
    shop_province = models.CharField(max_length=30, help_text='Enter then name of Province shop is located at.')
    shop_country = models.CharField(max_length=30, help_text="If not in Pakistan please specify your Country")
    location = models.CharField(max_length=120, help_text='Enter Street Address for your Shop for Verification')

    def __unicode__(self):
        return self.name

class Product(models.Model):
    title = models.CharField(max_length=120)
    description = models.TextField(blank=True, null=True)
    price = models.DecimalField(decimal_places=2, max_digits=20)
    active = models.BooleanField(default=True)
    categories = models.ManyToManyField('Category', blank=True)
    default = models.ForeignKey('Category', related_name='default_category', null=True, blank=True)
    hits = models.ManyToManyField(HitCount, blank=True)
    hitcounts = GenericRelation(HitCount, content_type_field='content_type', object_id_field='object_pk',)

DetailView for Shops:

class ShopDetailView(DetailView):
    model = Shop
    def get_context_data(self,*args, **kwargs):
        context = super(ShopDetailView, self).get_context_data(*args, **kwargs)

        return context

0 个答案:

没有答案