Django - access to external key manager from django templates

I have two models:

class Product(models.Model):
    name = models.CharField(max_length=255)

class ProductPhoto(models.Model):
    product = models.ForeignKey('Product', related_name='photos')
    is_live = models.IntegerField(choices=LIVE_CHOICES, default=1)

    live = LiveManager()

class LiveManager(Manager):
    def get_query_set(self):
        return super(LiveManager, self).get_query_set().filter(is_live=1)

I am trying to get live photos from product detail templates.

I tried

{% for photo in product.photos.live %}

who didn’t work and looked at the documents and could not find examples. Is it possible to call the foreign key manager from the template? Do I have to perform a function in a product model that returns a query to select a product?

Thank.

+5
source share
1 answer

, , . for, , . photos " ", ProductPhoto, objects ( ).

live, objects, objects , .. : ProductPhoto.objects.all(). , , Django objects.

, , live , , :

{% for photo in product.photos.all %}

"" . , , , (, admin). "" .

, :

class ProductPhoto(models.Model):
    product = models.ForeignKey('Product', related_name='photos')
    is_live = models.IntegerField(choices=LIVE_CHOICES, default=1)

    objects = models.Manager()
    live = LiveManager()

, objects , , . , live . , - "" :

class ProductPhotoQuerySet(models.query.QuerySet):
    def live(self):
        return self.filter(is_live=1)

class ProductPhotoManager(models.Manager):
    use_for_related_fields = True

    def get_query_set(self):
        return ProductPhotoQuerySet(self.model)

    def live(self, *args, **kwargs):
        return self.get_query_set().live(*args, **kwargs)

QuerySet Manager. live , . , , ProductPhoto.objects.live().filter(...), ProductPhoto.objects.filter(...).live().

, objects ( Django):

class ProductPhoto(models.Model):
    product = models.ForeignKey('Product', related_name='photos')
    is_live = models.IntegerField(choices=LIVE_CHOICES, default=1)

    objects = ProductPhotoManager()

, , :

{% for photo in product.photos.live %}
+23

All Articles