[Answer]-Integration of 'normal' Python class into a Django models class

1đź‘Ť

âś…

It sounds like you should not integrate your PythonXYZ class with a Django Model. Let Django manage the database (of individual x and y FloatField records). Your code handles the list logic which is really managing collections of Model instances. It doesn’t make sense to have methods on the Model that are intended to operate on something outside the scope of that individual Model instance. You might want a two-part solution — a Manager with a Collection class.

Write a custom Manager for your list-level load/save logic. That’s better than a purely generic class because it conceptually ties the list operations to the database records they are manipulating. The Manager will handle the initial loading of the Model instances into those x/y/z lists and saving the list back to the database. From the documentation:

Adding extra Manager methods is the preferred way to add “table-level”
functionality to your models. (For “row-level” functionality — i.e.,
functions that act on a single instance of a model object — use Model
methods, not custom Manager methods.)

A custom Manager method can return anything you want. It doesn’t have
to return a QuerySet.

Since the lists sound like entities in their own right, you might want a Collection class that provides the list with the do_some_complex_stuff(), size(), dump(), etc methods. This is the PythonXyz object you have now. You may be able to subclass list to avoid reimplementing append() and such. The Manager load() could return this Collection class while its save() turns a Collection into the Model instances for the database write.

As far as sharing the common code across your three apps.

  • You could use an abstract Model to hold the common code with concrete app Models.
  • If you need to access the commonality at the schema level, don’t use an abstract parent Model. (Then you’ll have a base table and individual tables holding only the app-specific columns.)
  • Proxy Models are only when you want different behavior and the schema is the same/shared.
👤JCotton

0đź‘Ť

completely integrate all the PythonXyz methods into the DjangoXyzModel class

Don’t. Leave the base classes separate, and then create model proxies that use MI to combine them, overriding behavior where appropriate.

Leave a comment