문제

I ahve a multi tenant Django database. All my multi tenant enabled models import from a class AccountSpecificModel, which as a FK to a class Account. Now I have some unique=True and unqiue_together in Meta, which do not specify account.

In my scenario, for AccountSpecificModel uniqueness has no menaing unless it takes care of account, which means I want to convert each unique to a unique_together with account, and simlar for unique_together.

How can I do this?

도움이 되었습니까?

해결책

If I'm understanding you correctly, this is what you want:

class Client(models.Model):
    account = models.ForeignKey(Account)
    email = models.EmailField()

    class Meta:
        unique_together = (('account', 'email'),)

Notice the "two-tuple" I assigned unique_together to. You can do a standard tuple, but if there is more than one field that you want to be unique together, you'll just have to change it anyway.

Now 500 different accounts can have a client with the email example@example.com, but no account can have 2 clients with the same email.

다른 팁

I did not understand your question fully, but I found that when implementing complicated django model class customizations one good solution is a class factory. I found that it is less complicated and less surprising than multiple inheritance and other magic.

def factory(superclass, arguments):
    class SomeClass(superclass):
        [...]

        class Meta:
            [...]

    return SomeClass

RealClass = factory(SuperClass, args)

I tried other approaches on a similar sounding problem for a while, but a factory for the class solved the problem in the end. Think about it, it may help you to solve your problem.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top