悪い例に入る前に要約すると、他:すべてのモデルでコードを記述して、現在ログインしているアカウントに選択肢を制限する必要がないアプリケーションを作成しようとしています(使用していません)認証、またはアカウントまたはログインの組み込み機能)。
つまり、私はこのようなことをする必要はありません:
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名前空間プロジェクト