two-scoops-of-django-3.x icon indicating copy to clipboard operation
two-scoops-of-django-3.x copied to clipboard

Proxy models still unclear

Open grondman opened this issue 4 years ago • 0 comments

Location within the Book

  • Chapter or Appendix: 22
  • Section: 3
  • Subsection: 2

Description

Some more explanation might be needed here, as I got quite confused after watching two of Daniel's YouTube video's on the same subject:

I guess my problem lies with the following code snippet

def save(self, *args, **kwargs):
    # If a new user, set the user's type based off the
    # base_type property
    if not self.pk:
        self.type = self.base_type
    return super().save(*args, **kwargs)

In the first video, it's suggested to add this custom save method to the proxy models themselves, whereas in the book and the second video, they are gone from the proxy models and instead it's put in the User superclass with base_type being set in the proxies and the User class.

To have a save method in each and every proxy model seems like a DRY issue, so that would favour having one in the User class, but... when this is done (like it's done in the book and the second video), I can no longer create a "proxy instance" using the User class, e.g. with the example in the book, if I would have a form using the User model, even if I select INVENTOR as a type, the custom save method there would still overwrite it with EATER. (Unless I'm missing something)

Possible Solutions

I'm not sure which way to go here, but I would expect that a correct implementation would enable me to:

  • Create an Inventor by using Inventor.objects.create(...)
  • Create an Inventor by using User.objects.create(...,type=User.Types.INVENTOR)

It would also help if the videos/book would have more consistency on this subject :)

Your full name so we can provide accurate credit within the book

Ivo Grondman

grondman avatar Aug 12 '20 07:08 grondman