Skip to content

Store comma separated values

deby edited this page Oct 18, 2018 · 5 revisions

↑ Parent: MagiModel utils

← Previous: Save choices values as integer rather than strings

While the recommended Django way of storing a list of values in a model is to use a separate model with ManyToMany, it can be quite costly, since you will need extra queries to retrieve the values. For simple list of values like strings, you can store them as comma separated values.

To do so, start your field name with c_, like so:

class Card(MagiModel):
    c_abilities = models.TextField(blank=True, null=True)

You may now access the CSV values in a convenient array like so:

print card.abilities # ["fly", "dance", "heal"] (list)
print card.c_abilities # "fly","dance","heal" (string)

You may limit your CSV values to a list of choices like so:

class Card(MagiModel):
    ABILITIES_CHOICES = (
        ('fly', _('Fly')),
        ('dance', _('Dance')),
        ('sing', _('Sing')),
        ('heal', _('Heal')),
    )
    c_abilities = models.TextField(blank=True, null=True)

Choices will not be enforced at the database level, but will help MagiForms show checkboxes.

You can get the list of translated CSV values using t_. It will return an ordered dictionary.

card.t_abilities # { 'fly': _('Fly'), 'dance': _('Dance'), 'heal': _('Heal') }

If choices are not provided or are provided without translations, it's going to return a dictionary with the same value as key and value.

Some methods are available directly in MagiModel to add and remove values from the CSV:

Name Description Parameters Return value
add_c Add strings to a CSV formatted c_something field_name, to_add None
remove_c Remove strings from a CSV formatted c_something field_name, to_remove None
save_c Completely replace any existing CSV formatted list into c_something field_name, c None

You still need to call save on your instance to save the values in database.

Example:

card = model.Card.objects.get(id=1)
card.add_c('abilities', ['fly', 'dance'])
card.save()

I. Introduction

II. Tutorials

  1. Collections
    1. MagiModel
    2. MagiCollection
    3. MagiForm
    4. MagiFiltersForm
    5. MagiFields
  2. Single pages
  3. Configuring the navbar

III. References

IV. Utils

V. Advanced tutorials

VI. More

Clone this wiki locally