gpt4 book ai didi

python - 如何避免在 Django views.py 中重复一大块代码

转载 作者:行者123 更新时间:2023-12-05 04:24:46 25 4
gpt4 key购买 nike

避免重复在多个类 View 中使用的一大块代码的最佳方法是什么?

我在几节课中重复这两行。

moderator = ServerModerator.objects.get(user=request.user)
server = Server.objects.get(Q(creator=request.user) | Q(moderators=moderator), Q(tag=server_tag))

我试过在 models.py 中创建一个函数,如下所示:

class Server(models.Model):
...
creator = models.ForeignKey(User , on_delete=models.CASCADE, related_name='user_servers')
moderators = models.ManyToManyField('ServerModerator', related_name='server')

def moderator_checker(self, current_user):
moderator = ServerModerator.objects.get(user=current_user)
server = Server.objects.get(Q(creator=current_user) | Q(moderators=moderator),Q(tag=self.tag))
return server

但这行不通。

views.py:

class TagsAndFlairsView(LoginRequiredMixin, View):
form_class = CreatePostTagForm
form_class_2 = CreateUserTagForm

def get(self, request, server_tag):
...
# moderator = ServerModerator.objects.get(user=request.user)
# server = Server.objects.get(Q(creator=request.user) | Q(moderators=moderator), Q(tag=server_tag))
check = Server.moderator_checker(request.user)
server_post_tags = check.post_tags.all()
server_user_tags = check.user_tags.all()
return render(request, 'servers/tags-flairs.html', {"server":check, "server_post_tags":server_post_tags, "server_user_tags":server_user_tags, "create_post_tag_form":create_post_tag_form, "create_user_tag_form":create_user_tag_form})

最佳答案

您可以创建自定义查询集:

class ServerQuerySet(models.QuerySet):
def check_moderator(self, current_user, tag):
moderator = get_object_or_404(ServerModerator, user=current_user)
self = self.get(Q(creator=current_user) | Q(moderators=moderator),Q(tag=tag))
return self

然后在您的服务器模型中,定义:

objects = ServerQuerySet.as_manager()

现在您可以:

server = Server.objects.check_moderator(request.user, tag) # EXAMPLE OF USER

QuerySets 还允许您做一些其他的事情。例如,您现在可以;在检查用户是否是版主之前过滤结果。这很好,例如,如果您有一个“事件”字段或任何类似的字段。 Server.objects.filter(server_is_active=True).check_moderator(request.user, tag).

Note: Generally, it is better to use get_object_or_404() instead of get() as it calls get() on a given model manager, but it raises Http404 instead of the model’s DoesNotExist exception.

关于python - 如何避免在 Django views.py 中重复一大块代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73432908/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com