Note that there are some explanatory texts on larger screens.

plurals
  1. POI want to write a generic function to pair two database fields
    primarykey
    data
    text
    <p>Let's say that I have two teams, <code>"red"</code> and <code>"black"</code>. And let's say that I have a <code>Story</code> class, which presents similar information in two very different ways, depending on your team:</p> <pre><code>class Story(models.Model): red_title = models.CharField() black_title = models.CharField() red_prologue = models.TextField() black_prologue = models.TextField() # ... and so on ... def get_field(self, genericName, team): """Return the field with suffix genericName belonging to the given team. &gt;&gt;&gt;self.get_field("prologue", "red") is self.red_prologue True &gt;&gt;&gt;self.get_field("title", "black") is self.black_title True """ assert(team in ["red", "black"]) specificName = "{}_{}".format(team, genericName) return self.__dict__[specificName] </code></pre> <p>I'm happy with the getter function, but I feel like I should be able to refactor the code which created the fields in the first place. I'd like a function that looks something like this:</p> <pre><code>def make_fields(self, genericName, fieldType, **kwargs): """Create two fields with suffix genericName. One will be 'red_{genericName}' and one will be 'black_{genericName}'. """ for team in ["red", "black"]: specificName = "{}_{}".format(team, genericName) self.__dict__[specificName] = fieldType(**kwargs) </code></pre> <p>But <code>self</code> and <code>__dict__</code> are meaningless while the class is first defined, and I think Django requires that database fields be class variables rather than instance variables.</p> <p>So... is there some way to create this <code>make_fields</code> function within Django, or am I out of luck?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload