Save and retrieve processed list in Django

I have one process list (like [["a","b","c"],["c","d","e"]]) in django and want to save such data in sql. I have built a class in model for such data as followed.

class Results(models.Model):
    batch_id = models.AutoField(primary_key=True)
    batch_cola = models.CharField(max_length=1000)
    batch_colb = models.CharField(max_length=1000)
    batch_colc = models.CharField(max_length=1000)
    owner = models.ForeignKey(User, on_delete=models.CASCADE)

I just want to know how could I edit the coding in the function for save such list and retrieve such list? I need the retrieved data can still be like [["a","b","c"],["c","d","e"]].

Here's what I do but error appears as "table XX_result has no column named owner_id”.

    for t in list:
        Results.objects.create(batch_cola=t[0], batch_colb=t[1], batch_colc=t[2])
    data = Results.objects.filter(owner=request.user)
    return render(request, "projects/results.html", {"datas": data})

2 answers

  • answered 2018-11-08 09:39 mistiru

    Did you create the migrations files (./ makemigrations) and apply them to the database (./ migrate)?

  • answered 2018-11-08 10:11 mistiru

    I'm not sure to understand your problem.

    Say we have a raw process list:

    raw_process_list = [["a", "b", "c"], ["c", "d", "e"]]

    And a Process model:

    from django.db import models
    class Process(models.Model):
        col_a = models.CharField(max_length=1000)
        col_b = models.CharField(max_length=1000)
        col_c = models.CharField(max_length=1000)
        owner = models.ForeignKey(User, on_delete=models.CASCADE)

    Here, are two Django helpers to save and retrieve such a list:

    def save_raw_process_list(rp_list, user):
        for raw_process in rp_list:
            cols = dict(zip(['col_a', 'col_b', 'col_c'], raw_process))
            Process.objects.create(owner=user, **cols)
    def retrieve_raw_process_list(user):
        return list(Process.objects
                    .values_list('col_a', 'col_b', 'col_c'))

    Then, when you have to store a process list, simply write:

    save_raw_process_list(raw_process_list, user)

    And when you have to get it back:

    raw_process_list = retrieve_raw_process_list(user)