在我遇到不好的例子之前总结一下,等:我正在尝试制作一个应用程序,我不必在所有模型中编写代码来限制对当前登录帐户的选择(我没有使用身份验证或帐户或登录的内置功能)。
即,我不想做这样的事情:
class Ticket(models.Model):
account = models.ForeignKey(Account)
client = models.ForeignKey(Client) # A client will be owned by one account.
content = models.CharField(max_length=255)
class TicketForm(forms.ModelForm):
class Meta:
model = Ticket
exclude = ('account',) #First sign of bad design?
def __init__(self, *args, **kwargs):
super(OrderForm, self).__init__(*args, **kwargs)
if self.initial.get('account'):
# Here's where it gets ugly IMHO. This seems almost
# as bad as hard coding data. It's not DRY either.
self.fields['client'].queryset = Client.objects.filter(account=self.initial.get('account'))
我的想法是使用以下自定义管理器创建一个Account(models.Model)
模型,并使用我的所有模型的多表继承对其进行子类化。不过,这让我感到非常头疼。我还需要account
在每个模型上使用外键吗?我可以访问某个模型实例的父类帐户吗?
class TicketManager(models.Manager):
def get_query_set(self):
return super(TicketManager, self).get_query_set().filter(account=Account.objects.get(id=1))
# Obviously I don't want to hard code the account like this.
# I want to do something like this:
# return super(ProductManager, self).get_query_set().filter(account=self.account)
# Self being the current model that's using this manager
# (obviously this is wrong because you're not inside a model
# instance , but this is where the confusion comes in for me.
# How would I do this?).
请忽略任何明显的语法错误。我在这里输入了整个内容。
这是我想到这样做的地方:Django Namespace project