Django REST Framework:使用另一个表进行过滤 [英] Django REST Framework : filtering with another table

查看:71
本文介绍了Django REST Framework:使用另一个表进行过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Django REST Framework来实现关联的计划系统,用户可以在其中订阅关联并接收其事件.每个关联可以有多个组(订阅该关联时可以选择一个组),因此每个组的事件通常是相同的,但是具有不同的地点和日期.

I'm using Django REST Framework to implement an associative schedule system, where a user can subscribe to an association and receive its events. Each association can have many groups (you choose yours when you subscribe to the association), so that the events are often the same for each group but with different places and dates.

该模型如下所示:

class Association(models.Model):
    name = models.CharField(max_length=40, blank=False, unique=True)
    description = models.CharField(max_length=500, blank=False)

class AssocMember(models.Model):
    class Meta:
        unique_together = (("user", "assoc"),)

    user = models.ForeignKey('user.User')
    assoc = models.ForeignKey('associations.Association')
    is_admin = models.BooleanField(default=False)
    group = models.SmallIntegerField(default=-1)

class Event(models.Model):
    name = models.CharField(max_length=40, blank=False)
    date = models.DateTimeField(blank=False)
    assoc = models.ForeignKey('associations.Association')
    group = models.IntegerField(blank=True, default=-1)

我需要在我的API中实现一个 get_queryset(),以返回与其用户组相对应的已连接用户的所有事件.但是为此,我必须在过滤期间为每个事件访问AssocMember,并创建一个自定义条件(如Python中的常规 .filter())

I would need to implement a get_queryset() in my API that returns all the events of the connected user corresponding to its group. But for that, I have to access AssocMember for each event during the filtering, and create a custom condition (like normal .filter() in Python)

使用Django REST过滤器的最佳方法是什么?

What is the best way to do so with Django REST filters ?

谢谢.

推荐答案

查看 ModelViewSet .您可以覆盖 get_queryset 方法以根据 request.user :

Check out a ModelViewSet. You can override the get_queryset method to filter based on request.user:

class EventViewSet(viewsets.ModelViewSet):
    def get_queryset(self):
        group = self.request.user.group  # Your models might need adjusting to do this
        return Event.objects.filter(group__in=group)

这篇关于Django REST Framework:使用另一个表进行过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆