'Representing Django M2M data export in a CSV

The problem I am trying to solve is to export all the entries of a Django model as CSV. The field names are supposed to be headers, with each row having an appropriate value under each column. The challenge here is that the model has a few M2M relationships. Each associated M2M model has multiple fields in it. I have added a subset of the main model and some related models below:

class Semester(TimeStampedModel):

    title = models.TextField()
    uuid = models.UUIDField(blank=False, null=False, default=uuid4, editable=False, verbose_name=_('UUID'))


class CreditClass(TimeStampedModel):

    title = models.TextField()
    category = models.CharField(max_length=32)
    is_active = models.BooleanField(default=False)
    credits = models.IntegerField()


class Student(TimeStampedModel):

    name = models.TextField()
    age = models.IntegerField()

    active_semesters = models.ManyToManyField(Semester)
    enrolled_classes = models.ManyToManyField(CreditClass)

Each student will have a different count for associated model entries. For example, Student A in the 3rd semester will have an association with 3 Semester objects while a student B in the 5th Semester will have 5. The credit class count is also the same case. Therefore, defining static headers in CSV is difficult, given the data will vary on each row.

That said, the only plausible solution in my mind: Export each M2M model data in the form of a list of JSON, dump the list via Python json.dumps, and add the dumped CSV under the respective column for each row.

Now, the questions:

  • Does the above-mentioned solution make sense? How can it be improved?
  • What other ways can there be to export dynamic M2M data in CSV?
  • If not CSV, what other file can be used for data export?

Feel free to comment if you need more information/clarification on the scenario. Thanks



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source