Django: Jak zorganizować ten wielki bałagan na wzór / menedżer / projekt?
Podsumowując, zanim przejdę do złych przykładów, i in.: Próbuję stworzyć aplikację, w której nie muszę pisać kodu we wszystkich moich modelach, aby ograniczyć wybory bieżącego zalogowanego konta (nie używam Auth lub wbudowane funkcje konta lub logowania).
tj. janie chcę zrobić coś takiego:
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'))
Moim pomysłem jest stworzenieAccount(models.Model)
model z następującym menedżerem niestandardowym i podklasuj go za pomocą dziedziczenia wielostolikowego ze wszystkimi moimi modelami. To jednak daje mi ogromny ból mózgu. Czy nadal będę potrzebowaćaccount
klucz obcy na każdym modelu? Czy mogę uzyskać dostęp do konta klasy nadrzędnej dla określonej instancji modelu?
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?).
Proszę zignorować wszelkie błędy błysku składni. Wpisałem to wszystko tutaj.
Oto pomysł, aby to zrobić:Projekt przestrzeni nazw Django