Django:限制模型数据 [英] Django: limiting model data
问题描述
假设我有以下模型(有依赖关系):
我正在寻找一种方法来限制我可以通过模型获得的查询集。 p>
公司
| - 节
| | - 员工
| | - 任务
| ` - 更多型号...
| - 客户
| | - 合同
| | - 帐户
| ` - 其他伟大的模型...
` - 更多的模型...
应该注意的是,我的真实模型更深入,而不是真正的业务。
使用上下文处理器,我添加了一个公司实例请求:
def magic_view(request):
request.company#是公司模型的一个实例
现在我的问题是什么是限制公司的子模型访问公司请求实例的最佳方式我可以让它像 task = Task.objects.get(pk = 4,section__task = task)
但是,如果我的模型结构越来越深,这是一个糟糕的方法。
编辑:我可以把对方的模型给公司但这是存储关系冗余的好习惯吗? 编辑2:不是。请参阅使用冗余关系是否不好?。
我以下列方式解决了:
首先我创建了一个CurrentCompanyManager
class CurrentCompanyManager(models.Manager):
def __init __(self,field,* args,** kwargs )
super(CurrentCompanyManager,self).__ init __(* args,** kwargs)
self .__ field_name = field
def on(self,company):
return self.filter(** {self .__ field_name +'__id__exact':company.id})
比我经理添加到需要它的所有型号。
class Employee(models.Model):
#一些字段和关系
objects = CurrentCompanyManager(section__company)
类帐户(models.Model):
#一些字段和关系
对象s = CurrentCompanyManager(customer__company)
现在我可以轻松地限制视图中的模型数据。
def magic_view(request):
Employee.objects.on(request.company).all()
应该是不言自明的。如果没有,请问我。
I'm searching in a way to limit the queryset which I can get through a model.
Suppose I have the following models (with dependencies):
Company
|- Section
| |- Employee
| |- Task
| `- more models...
|- Customer
| |- Contract
| |- Accounts
| `- other great models ...
`- some more models...
It should be noted that my real models are much deeper and it's not really about business.
With a context processor I have added a company instance to request:
def magic_view(request):
request.company # is a instance of Company model
Now my question is what is the best way to limit the access to the child models of Company to the request instance of company?
I could make it like task = Task.objects.get(pk=4,section__task=task)
, but this is a bad way if my model structure is getting deeper.
Edit: I could give each other model a foreign key to company, but is this a good practice to store relations redundant? Edit 2: No it isn't. See Is it bad to use redundant relationships?.
I solved it the following way:
First I've created a CurrentCompanyManager.
class CurrentCompanyManager(models.Manager):
def __init__(self,field,*args,**kwargs):
super(CurrentCompanyManager,self).__init__(*args,**kwargs)
self.__field_name = field
def on(self,company):
return self.filter( **{ self.__field_name + '__id__exact':company.id } )
Than I added the manager to all models where I need it.
class Employee(models.Model):
# some fields and relationships
objects = CurrentCompanyManager("section__company")
class Accounts(models.Model):
# some fields and relationships
objects = CurrentCompanyManager("customer__company")
And now I can easily limit the model data in the view.
def magic_view(request):
Employee.objects.on(request.company).all()
It should be self-explanatory. If not, then ask me.
这篇关于Django:限制模型数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!