开发者

django views - accessing a m2m field in a generic view

开发者 https://www.devze.com 2023-02-11 01:32 出处:网络
I\'ve stumbled upon this issue and my noob brain got fried trying to resolve it. I feel like there\'s some basic concepts here that I\'m missing.

I've stumbled upon this issue and my noob brain got fried trying to resolve it. I feel like there's some basic concepts here that I'm missing.

So I have this "Films" model with category choice field and a m2m relationship to a "Directors" model, and I'm trying to write 2 different views, one that returns a list of films filtered by category and one that returns a list of films filtered by director. The first one is easy, but I just don't know how to get the director model's name field to create the second filter.

So I have this models (i've taken the irrelevant stuff out including the category thing i mentioned above)

class Director(models.Model):
    name = models.CharField(max_length=50)
    web = models.URLField(blank=True, help_text= "opcional")


class Film(models.Model):

    name = models.CharField(max_length=50)
    slug = models.SlugField(max_length= 15)
    director = models.ManyToManyField(Director, blank=True, help_text= "opcional")

this url

(r'^peliculas/director/(?P<director>\w+)/$', 'filtered_by_director'),

and this view

def filtered_by_director(request,director):
    return list_detail.object_list(
        request, 
        queryset = Film.objects.filter(director.name=director),
        template_name ='sections/film_list.html',
        template_object_name = 'film',
        paginate_by = 3

        开发者_运维问答)

The same template is supposed to be used by both views to render the relevant list of objects The view doesn't like the filter i'm using at the queryset for the m2m field, but I have no clue how to do it really, I've tried whatever I could think of and it gives me a "keyword can't be an expression" error

Any help to this lowly noob will be appreciated.


Line queryset = Film.objects.filter(director.name=director),

needs to read: queryset = Film.objects.filter(director__name=director),

Field lookups are done by __ double underscore syntax: http://docs.djangoproject.com/en/dev/topics/db/queries/#field-lookups


In your filter, try specifying the director name like (documentation):

filter(director__name=director)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号