Samoht
Samoht

Reputation: 49

Django ModelField custom attribute

Very simple question: can you make a custom attribute for a Field? I have a Customer model with a bunch of Fields. Charfields, ForeignKeys,IntegerFields, BooleanFields etc. etc.

When the form gets submitted for a new customer I want to export the data to an existing excel template, where cell names are B1 and value B2 for instance. So I was thinking to just give every field an 'cell position' attribute so I can just loop through the cells and easily assign each column their value, something like name = models.CharField(verbose_name='Name',max_length=30,'cell position' = 'B2'),

Would that be possible? If so or not, how would I go about doing this?

Upvotes: 1

Views: 280

Answers (1)

Yevhenii Kosmak
Yevhenii Kosmak

Reputation: 3860

You are attempting to muddle together the data logic and business logic. You described one use case for that model: when it's to be saved. The cell position you had mentioned is only applicable to that use case and would be useless when you, for example, need to find a customer by its name.

Much senseful would be to put these constants to the file which is responsible for saving Customer to a excel file, like this:

class CustomerExcelExporter():
    CUSTOMER_FIELD_TO_FILE_CELLS = {
        "name": "B2",
        # ...
    }

    _worksheet: Worksheet
    _customer: Customer

    # ...

    def _fill_customer_own_fields(self):
        for field, cell in self.CUSTOMER_FIELD_TO_FILE_CELLS:
            self._worksheet.write(cell, getattr(self._customer, field)

Upvotes: 1

Related Questions