0

Say I have a model with many attributes that are somewhat related

class ManyFields(models.Model):
  a = models.CharField(…)
  b = models.CharField(…)
  c = models.CharField(…)
  d = models.CharField(…)
  …
  # This works -ish, but am unsure if it is what is convention/needed
  def many_fields_simple_array(self):
    return [self.a,self.b,self.c,self.d,]

and later in the view, where there isn't much real estate (say mobile), I want to just provide some sort of concatenated version of the fields. Instead of

<td>{{many_fields.a}}<td>
<td>{{many_fields.b}}</td>
<td>{{many_fields.c}}</td>
…

I would like to just have

<td>{{many_fields.many_fields_simple_array()}}<td>

and it will look AWESOME :) I can handle the rendering of HTML/text, CSS, visual part (kind of going for a red-light/green-light for each field), but I don't know the repercussions of writing a Model function or a Manager. I am unsure after reading the docs/intro.

Notes/Assumptions:

  • I come from a JS/Angular world, so I would assume an array would be perfect for what I need, but I think I might be missing something
  • I assume an array, because in the template I could iterate over them quite easily. Open to other suggestions
chris Frisina
  • 19,086
  • 22
  • 87
  • 167

2 Answers2

1

In this situation it makes sense to take the approach you are currently taking and write a function in your model. In Python, a function inside a class is called a method, so we use the term model method.

The Manager of an object in Django is used to determine how queries on that model are performed via Model.objects.<query_function>. In your situation, you want an individual instance of the model to be handled differently/uniquely, not necessarily for the querying of the model to be different. Thus, a model method to get the desired behavior for an instance of the ManyFields model makes perfect sense.

Furthermore, the best practice would be to add the model method as a custom field to a serializer that is used to retrieve the data for the front end. This Stack Overflow answer shows how to do so. By doing this, your object will have the field ready to be accessed so that you can have the short and concise version you are looking for.

shacker
  • 14,712
  • 8
  • 89
  • 89
Rohan Varma
  • 1,145
  • 6
  • 11
0

Using this line will return the values in a dictionary. ManyFields.objects.filter(name='Beatles').values()

[{'a': 1, 'b': 'Beatles Blog', 'c': 'All the latest Beatles news.'}]

Similar question was answered here: Printing Objects in Django