2

I am newbie in Django and wanted to know a basic thing:

I have 2 model :

class QuizCat(models.Model):

    cid = models.IntegerField()
    c_name = models.CharField(max_length=200)

class Quiz(models.Model):

    Qid = models.IntegerField()
    cat_id = models.ForeignKey(QuizCat, on_delete=models.CASCADE)
    name = models.CharField(max_length=200)

I want to insert data in database using 1 csv file such that data gets inserted in both QuizCat model and Quiz model. also what should be the structure of csv file ?

1
  • I think this is not possible using one CSV, as you have ForeignKey relation Commented Mar 19, 2020 at 7:02

1 Answer 1

1

You dont need to add id field it will be added by django by default

models.py

class QuizCat(models.Model):
    c_name = models.CharField(max_length=200)

class Quiz(models.Model):
    cat_id = models.ForeignKey(QuizCat, on_delete=models.CASCADE)
    name = models.CharField(max_length=200)

views.py

def uploadFile(request):
    try:
        csv_file = request.FILES["csv_file"]#change csv_file according to your form input name
        file_data = csv_file.read().decode("utf-8")     
        lines = file_data.split("\n")
        for line in lines:                      
            fields = line.split(",")
            fields = [i.trim() for i in fields ]
            name = fields[0]
            cat = fields[1]
            qcat,created=QuizCat.objects.get_or_create(c_name=cat)
            Quiz.objects.get_or_create(cat_id=qcat,name=name)
    except e:
        raise
    return HttpResponse("Success")

CSV

Quiz name,QuizCat name

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.