-2

I've already broken down models.py into separate model files.

One of model file is getting huge, and I want to break it apart, but don't know how.

One way I can think of is, break methods into several classes (as mixins) and inherit them. but not sure if it's the best way to go about it.

  • Edit,

This is different question than possible duplicates.

When a single model (such as Book) gets large, how do you split it up?

possible duplicates doesn't ask the question nor answer it.

eugene
  • 39,839
  • 68
  • 255
  • 489
  • 1
    Possible duplicate of [models.py getting huge, what is the best way to break it up?](http://stackoverflow.com/questions/1160579/models-py-getting-huge-what-is-the-best-way-to-break-it-up) – Abijith Mg May 16 '17 at 05:14
  • @AbijithMg: I can't find an answer for my question, when one of your model (not models.py) gets large, how do yo deal with it? – eugene May 16 '17 at 05:57
  • You can split your logic into view, one of the solutions. – Kairat Kempirbaev May 16 '17 at 06:27

1 Answers1

0

Mixins sound like they'd solve your problem nicely. You can put another file in your models directory called mixins.py and do something like the following:

models/mixins.py

class BookMixin(object):
    def is_in_print(self):
        ...
    def calculate_cost(self, number_ordered):
        return self.price * number_ordered

models/book.py

from .mixins import BookMixin

class Book(BookMixin, models.Model):
    price = models.DecimalField()
    title = ...

Then in your view, you could do something like the following:

purchased_book = Book.objects.get(...)
subtotal = purchased_book.calculate_cost(3)
panatale1
  • 373
  • 1
  • 10
  • One thing to know is that if you do this, your migrations get screwed up should you later try to remove any mixins from the model class definition. Not a major issue, because you can empty them out down to a single `pass` statement instead of completely deleting them. – nigel222 Mar 10 '20 at 14:35