Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
82 views
in Technique[技术] by (71.8m points)

python - How to use the two fields as many to many fields in another table?

Be Patient! Am new to the python and Django, and am trying to implement feedback form for customer, each customer has unique question set. There are three tables such question, answer, customer info. When user submit the question it should be in the answer table, there i wanted to map question and answer choices. How to do that?

my models.py

import uuid

from django.core.validators import MinValueValidator, MaxValueValidator
from django.db import models
from django.db.models import Max
from django import forms



class Questions(models.Model):

    fields = ['question',
              'field_type',
              'answers']
    field_choices=(("radio" ,"radio"),
                  ('checkbox', 'checkbox'),
                  ('text', 'text'))

    question=models.TextField(verbose_name='question',blank=False,null=False,default='')
    # field_type = models.TextField(verbose_name='field_type', blank=False, null=False,choices=field_choices,default='Domain')
    # field_type = models.TextField(verbose_name='field_type', blank=False, null=False, default='')
    field_type = models.TextField(verbose_name='answer_choices', blank=False, null=False,choices=field_choices,default='')
    answer_choice = models.TextField(verbose_name='answer_choices', max_length=128,blank=True, default='')


    # def __str__(self):
    #     return self.question

class Customer(models.Model):
    Cust_id=models.CharField(verbose_name='Cust_id',editable=False,max_length=128,blank=False,null=False,default='',db_index=False)
    # id = models.CharField(primary_key=True, editable=True, max_length=10,default='')
    Domain=models.CharField(verbose_name='Domain',max_length=128,blank=False,null=False,default='')
    name = models.CharField(verbose_name='Name', max_length=128, blank=False, null=False,default='')
    Address = models.CharField(verbose_name='Address', max_length=128, blank=False, null=False,default='')
    Cust_Address2 = models.TextField(verbose_name='Cust_Address2', blank=False, null=False, default='')
    Cust_City = models.TextField(verbose_name='Cust_City', blank=False, null=False, default='')
    # city_code = models.TextField(verbose_name='city_code', blank=False, null=False, default='')
    city_code = models.ManyToManyField('Locations',related_name='City_code',default='',db_index=True)
    sublocation=models.CharField(verbose_name='sublocation', max_length=128, blank=False, null=False,default='')
    sublocation_code=models.CharField(verbose_name='sublocation_code', max_length=128, blank=False, null=False,default='',db_index=False)
    Country = models.TextField(verbose_name='Country', blank=False, null=False, default='')
    question=models.ManyToManyField('Questions',related_name='customer_question',default='')

    # class Meta:
    #     indexes = [
    #         models.Index(fields=['Cust_id', 'Domain','name','Address','Cust_Address2','Cust_City','city_code','sublocation','Country','question']),
    #         models.Index(fields=['Cust_id'], name='Cust_id_idx'),
    #         models.Index(fields=['Domain'], name='Domain_idx'),
    #         models.Index(fields=['name'], name='name_idx'),
    #         models.Index(fields=['Address'], name='Address_idx'),
    #         models.Index(fields=['Cust_Address2'], name='Cust_Address2_idx'),
    #         models.Index(fields=['Cust_City'], name='Cust_City_idx'),
    #         models.Index(fields=['city_code'], name='city_code_idx'),
    #         models.Index(fields=['sublocation'], name='sublocation_idx'),
    #         models.Index(fields=['Country'], name='Country_idx'),
    #         models.Index(fields=['question'], name='question_idx'),
    #     ]

    def questionlist(self):
        question = models.ManyToManyField('Questions', related_name='customer_question')
        question_value=list(self.question.values('question'))
        question_list=[]
        for value in question_list:
            question_list.append(value.get('question'))
enter code here
        return question_value

    def citycodelist(self):
        city_code = models.ManyToManyField('Location', related_name='City_code', default='')
        city_code_value = list(self.city_code.values('city_code'))
        city_code_list = []
        for value in city_code_list:
            city_code_list.append(value.get('city_code'))
        return city_code_value


    # def __str__(self):
    #     return self.Cust_id

class Answer(models.Model):
    fields = ['name',
              'question',
              'Answer']

    name = models.CharField(verbose_name='Name', max_length=128, blank=False, null=False)
    cust_id= models.ManyToManyField('Customer', related_name='customer_id')
    # cust_id = models.CharField(verbose_name='Cust_id', max_length=128, blank=False, null=False,default='')
    # Aquestion = models.ManyToManyField('Questions', related_name='customer_Aquestion', default='')
    # question = models.CharField(verbose_name='Question', max_length=128, blank=False, nul=False)
    # AAnswer = models.ManyToManyField('Questions', related_name='customer_Aanswer', default='')
    # AAnswer = models.F('Questions', related_name='customer_AAnswer', default='')
    Aquestion = models.CharField(verbose_name='Question', max_length=128, blank=False,default=`enter code here`'')
    AAnswer = models.CharField(verbose_name='Answer', max_length=128, blank=False,default='')

    def custidlist(self):
        cust_id = models.ManyToManyField('Customer', related_name='customer_id')
        question_value = list(self.cust_id.values('cust_id'))
        question_list = []
        for value in question_list:
            question_list.append(value.get('cust_id'))

        return question_value
    def questionlist(self):
        Aquestion = models.ManyToManyField('Questions', related_name='customer_Aquestion')
        question_value=list(self.Aquestion.values('Aquestion'))
        question_list=[]
        for value in question_list:
            question_list.append(value.get('Aquestion'))

        return question_value

    # Answer = models.ManyToManyField('Answerchoices', related_name='customer_question', default='Domain')
    print("[answer]", AAnswer)

    def answerlist(self):
        AAnswer = models.ManyToManyField('Questions', related_name='Answerchoices')
        ans_value = list(self.AAnswer.values('AAnswer'))
        ans_list = []
        for value in ans_list:
            ans_list.append(value.get('AAnswer'))

        return ans_value
    # def __str__(self):
    #     return self.name```

views.py

from django.core import serializers
from django.shortcuts import render
import sqlite3
# Create your views here.
from django.utils.datetime_safe import datetime
# import numpy as np
from . forms import *
from django.template import loader
conn = sqlite3.connect('Feedback.db')
# from pymongo import MongoClient
# from bson.json_util import dumps
import json

from django.http import HttpResponse
from django.http import JsonResponse
from . models import *

# from pymongo import MongoClient

def index(request):
    template = loader.get_template('feedques.html')
    city_code=Locations.objects.values('city_code')
    print("---->",city_code)
    json_data=json.dumps(list(city_code))
    print("---->", json_data,type(json_data))
    context = {}
    return HttpResponse(template.render(context, request))


def feedbackques(request, self=None):
    results={}
    if  request.method == "POST":
      if (request.POST['cust_id']):
          inputdata=request.POST['cust_id']
          print(inputdata)


          if customerform().is_valid():
              instance = customerform.save(commit=False)

              instance.save()
              print(instance)
          #result = [Customer.objects.filter(Domain=inputdata).values_list('question__question'),Customer.objects.filter(Domain=inputdata).values()]
          customermdl=Customer.objects.all()
          answer_idsave=Answer(cust_id=inputdata).save()
          r1 = Customer.objects.filter(Cust_id=inputdata).values()
          r2=list(Customer.objects.filter(Cust_id=inputdata).values_list('question__question','question__field_type','question__answer_choice'))

          print(r2,type(r2))



          # r11 = Customer.objects.filter(Domain=inputdata).values_list('question__answer_choice2')
          # r12 = Customer.objects.filter(Domain=inputdata).values_list('question__answer_choice3')
          # r13 = Customer.objects.filter(Domain=inputdata).values_list('question__answer_choice4')

          from itertools import chain

          # results = list(chain(r10,r11,r12,r13,r2,r3,r4))
          # results = list(r2)
          # my_array = np.array(results)
          # print("arraytype",my_array)
          result=json.dumps(r2)
          # print("arrajson", result)
          # result = serializers.serialize('json', self.results())
          print("------------------>",result,type(result))    #django.db.models.query.QuerySet
          json_docs = []
          custr_id = Customer.objects.filter(Cust_id=inputdata).values()
          print(custr_id)
          # user_ids = Customer.objects.filter(Cust_id=inputdata)
          # instance = Answer.objects.create(cust_id=user_ids)
          #
          # for user_id in user_ids:
          #     instance.cust_id.add(user_id)
          #     print('m2M Succeeded')
          mimetype = "application/javascript"
          return HttpResponse(result, content_type=mimetype)


          print("entered answerview")
          # import cgi
          # form = cgi.FieldStorage()
          # pay = form.getvalue('pay');
          # if label in request.
      else:
          input_names = [name for name in request.POST.keys() if name.startswith('ans')]
          print(request.POST.keys())
          for input_name in input_names:
              cust_answer = request.POST[input_name]
              cust_id = request.POST['cust_id']
              print("cust_id else",cust_id)
              # custr_id=Customer.objects.filter(cust_id=cust_id).values()
              # print(custr_id)
              print("response_ans", cust_answer)
              saveanswer = Answer(Aquestion=input_name, AAnswer=cust_answer,cust_id=cust_id)
              # saveanswer = Answer(Aquestion=input_name, AAnswer=cust_answer, cust_id=custr_id)
              saveanswer.save()
              if answerform().is_valid():
                  instance = answerform.save(commit=False)
                  # instance = Answer.objects.create('name')

                  # instance.Aquestion.add(input_name)
                  # instance.AAnswer.add(cust_answer)
                  print(instance)

                  c = min([len(input_names)])
                  print(len(input_names))

                  print("answer saved")

          return render(request, 'feedques.html', {'message': "answer submitted!!!"})
 
question from:https://stackoverflow.com/questions/65560239/how-to-use-the-two-fields-as-many-to-many-fields-in-another-table

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...