shibs
shibs

Reputation: 53

Proxy model for Multiple models in Django

I would like to display a model in the django admin but with the logic to choose between 2 models to display.

Current Implementation:

Models

class User(models.Model):
   created = models.DateTimeField(auto_now_add=True, null=True)
   last_updated = models.DateTimeField(auto_now=True)
   name = models.CharField(max_length=30, blank=True)

class ExpectedNames(User):
   class Meta:
      proxy=True`

Admin

@admin.register(ExpectedNames) class ExpectedNamesAdmin(admin.ModelAdmin): date_hierarchy = 'created'

What I Would like to DO: # something like this

Models

class User(models.Model):
    created = models.DateTimeField(auto_now_add=True, null=True)
    last_updated = models.DateTimeField(auto_now=True)
    name = models.CharField(max_length=30, blank=True)

class User2(models.Model):
    created = models.DateTimeField(auto_now_add=True, null=True)
    last_updated = models.DateTimeField(auto_now=True)
    name = models.CharField(max_length=30, blank=True)

class ExpectedNames(User):
    class Meta:
        proxy=True

    if name == "Rick":
    return User
    else:
    return User2

Admin

@admin.register(ExpectedNames) class ExpectedNamesAdmin(admin.ModelAdmin): date_hierarchy = 'created'

Any suggestions not sure if this is the correct way to do this.

Upvotes: 1

Views: 1997

Answers (2)

Kseniya ksinn
Kseniya ksinn

Reputation: 1

I use magic method new in same situation.

I have model Documen with field document_type. If document_type is 'contract' i want ContractProxy, if 'offer' - OfferProxy. For do this I create new proxy:

class RelatedDocumentProxy(Document):

    class Meta:
        proxy = True

    def __new__(cls, *args, **kwargs):
        doc_type = args[1]
        if doc_type == 'contract':
            return ContractProxy(*args, **kwargs)
        return OfferProxy(*args, **kwargs)

document_type is first field and will first arg who pass to method

Upvotes: 0

Golgorie Haus
Golgorie Haus

Reputation: 55

I think this is not possible as it states in the Django Documentation:

Base class restrictions: A proxy model must inherit from exactly one non-abstract model class. You can’t inherit from multiple non-abstract models as the proxy model doesn’t provide any connection between the rows in the different database tables. A proxy model can inherit from any number of abstract model classes, providing they do not define any model fields. A proxy model may also inherit from any number of proxy models that share a common non-abstract parent class.

https://docs.djangoproject.com/en/dev/topics/db/models/#proxy-models

Upvotes: 1

Related Questions