我是 Django 新手,遇到了一些困难,我对使用 Django 自定义模型管理器的正确方法感到困惑:
慈善机构/models.py:
from django.db import models
from accounts.models import User
class Benefactor(models.Model):
Level = ((0, 'Beginner'), (1, 'Intermediate'), (2, 'Expert'))
user = models.OneToOneField(User, on_delete=models.CASCADE)
experience = models.SmallIntegerField(choices=Level, default=0)
free_time_per_week = models.PositiveSmallIntegerField(default=0)
class Charity(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
name = models.CharField(max_length=50)
reg_number = models.CharField(max_length=10)
class TaskManager(models.Manager):
def related_tasks_to_charity(self, user):
my_charity = str(Charity.objects.get(user = user))
return self.filter(charity = my_charity)
def related_tasks_to_benefactor(self, user):
my_bonefactor = str(Benefactor.objects.get(user = user))
return self.filter(assigned_benefactor = my_bonefactor)
def all_related_tasks_to_user(self, user):
return self.filter(state = "P")
class Task(models.Model):
gen_choice = (('F', 'Female'), ('M', 'Male'))
sta_choice = (('P', 'Pending'), ('W', 'Waiting'), ('A', 'Assigned'), ('D', 'Done '))
# id = models.AutoField() !REMOVE id FIELDS
assigned_benefactor = models.ForeignKey(Benefactor, null=True, on_delete=models.SET_NULL)
charity = models.ForeignKey(Charity, on_delete=models.CASCADE, related_name='User_Charity')
age_limit_from = models.IntegerField(blank=True, null=True)
age_limit_to = models.IntegerField(blank=True, null=True)
date = models.DateField(blank=True, null=True)
description = models.TextField(blank=True, null=True)
gender_limit = models.CharField(max_length=50, blank=True, null=True)
state = models.CharField(max_length=50, choices=sta_choice, default='Pending')
title = models.CharField(max_length=100)
objects = TaskManager()
我的问题在这里,这三个定义:
class TaskManager(models.Manager):
def related_tasks_to_charity(self, user):
my_charity = str(Charity.objects.get(user = user))
return self.filter(charity = my_charity)
def related_tasks_to_benefactor(self, user):
my_bonefactor = str(Benefactor.objects.get(user = user))
return self.filter(assigned_benefactor = my_bonefactor)
def all_related_tasks_to_user(self, user):
return self.filter(state = "P")
def related_tasks_to_charity: 在此函数中,以查询集格式返回所有作为慈善机构提供给用户的任务。
例如,如果用户没有慈善机构,显然没有任何任务作为慈善机构提供给他,并且您的函数必须在查询集中返回值 none。
def related_tasks_to_benefactor: 在此函数中,以查询集格式返回所有作为恩人给予用户的任务。
例如,如果用户不是恩人,那么显然没有任何任务作为恩人给予他,并且您的函数必须以查询集的形式返回 none 的值。
def all_related_tasks_to_user: 在此函数中,以查询集格式返回用户有权访问的所有任务。
用户可以访问状态为待处理或作为捐助者或慈善机构提供给用户的任务。
该函数的功能是将所有这些Tasks作为查询集返回......