Django: How to organize this great model / manager / design?

To summarize before I get into bad examples, etc .: I am trying to create an application in which I do not need to write code in all my models in order to limit the selection to the current account (I'm not using Auth or built-in functions for account or login).

those. I do not want to do something like this:

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 where it gets ugly IMHO. This seems almost
                        # as bad as hard coding data. It 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 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

+3
3

, Django.

- , / () , Django auth, .

, , , . django-granular-permissions - ( /) django-authority.

Django 1.2 , django- .

- - , . , , , ().

, , , . . Django django. , , Rails .

, , django-authority, , , .

+7

, django.contrib.auth, , . - :

def some_view(request):
    account = get_account_by_request(request)

. , , , . ( ) - .. .

+2

, threadlocals, , , :)

, , .

+1
source

Source: https://habr.com/ru/post/1729941/


All Articles