Generate input fields based on a input and store it properly - python

I have a field called subjects that asks users how many subjects do they have and based on the number they input I want to generate the input fields of same number. And How and where do I store those inputs.
MODELS.PY
#this field will determine how many input fields to generate
subjects = models.IntegerField()
VIEWS.PY
def generate_forms(request):
no_of_fields = request.GET.get('subjects')
if no_of_fields:
#generate other inupts
#save it in the database
Besides generating the input, how do I save those data in the database.
Thanks in advance

If you use postgres you can use django postgres specefic models fields(Like ArrayField).django specefic fields documention
For another databases you can create model for your subjects and for each subject you can insert new data in Subject model.
class Subject(models.Model):
desc = models.CharField(max_length=50)
other_filed = models.ForeignKey(OtherModel)
def generate_forms(request):
other_field = 1
subjects = request.GET.get('subjects')
if subjects and subjects != '':
for subject in subjects:
Subject.objects.create(desc=subject, other_field=other_field)

Related

Queryset for models FK relations in django

These are my models and fields:
Models.py
Course:
title
slug
CoursePrerequisite
this_course = ForeignKey(Course)
prerequisite_of_course = ForeignKey(Course)
Curriculum:
course = ForeignKey(Course,)
title
slug
Enrollment:
student = ForeignKey(User)
curriculum =ForeignKey(Curriculum)
date
Brif of my system:
As seen from my model file, in this system, the courses have a
pre-requisite state.Untile preson can't pass pre-requisite of course, can't take the course.
Each course is presented for enrollment in model named:
'Curriculum'.
And finally my problem is:
In fact, I know that I must first check student enrollment and find the 'Curriculum' that he have,and by this, find all course of student. Then,among the course I will find the course that have prerequisite_of_course and finally check for student for each of this prerequisite course check that student enroll in course curriculum!
It's very hard for me to write this query? Can you help me?
Check this, this can help your query
# all student enrollments
all_enrollment = Enrollement.objects.filter(student=user)
# all students curriculum_ids
all_curriculum_ids = all_enrollment.values_list('curriculum', flat=True)
# all curriculum object list
all_curriculum = Curriculum.objects.filter(pk__in=all_curriculum_ids)
# all student curriculum courses
all_courses_ids = all_curriculum.values_list('course', flat=True)
# we have all courses that student participated
all_courses = Course.objects.filter(pk__in=all_courses_ids)
# Now getting prerequisite_of_course ids
all_prerequisite_of_course_ids = CoursePrerequisite.objects.filter(this_course=this_course,prerequisite_course__isnull=False).value_list('prerequisite_course')
# here checking if student took all prequisite courses
for prerequisite_of_course_id in all_prerequisite_of_course_ids:
if all_courses.filter((pk__in=prerequisite_of_course_id).exists():
print("Paticipated")
else:
print("In this course id student did not participated", prerequisite_of_course_id)
print("Tell Student to go and complete this course")

How to join tables with multiple foreign keys and get filtered data in Django?

I have two models like this:
class Question(models.Model):
ques_id = models.IntegerField()
test_id = models.ForeignKey('exam.Test')
ques = models.TextField()
class UserAnswer(models.Model):
user = models.ForeignKey('exam.User')
test_id = models.ForeignKey('exam.Test')
ques_id=models.ForeignKey('exam.Question')
user_ans = models.TextField()
I need to execute this query to get the correct 'ques' field values.
SELECT A.ques_id, B.ques, A.user_ans FROM useranswer A
inner join question B on B.ques_id= A.ques_id and B.test_id =A.test_id
WHERE A.user_id=1 and B.test_id='101'
So far what I have done:
UserAnswer.objects.filter(test_id=test_id, user_id=user_id).values('ques_id', 'ques_id__ques','user_ans')
But it doesn't returning the right 'ques' field values because it doesn't considering the B.test_id =A.test_id section. How to retrieve it???
First of all, your field names are misleading. Do not
suffix foreign key fields with _id! Accessing them as attributes returns model instances and django provides the _id suffixed attributes to access the actual keys implicitly:
class Question(models.Model):
test = models.ForeignKey('exam.Test')
ques = models.TextField()
# is this supposed to be the primary key? Don't do that
# ques_id = models.IntegerField()
class UserAnswer(models.Model):
user = models.ForeignKey('exam.User')
ques = models.ForeignKey('exam.Question')
user_ans = models.TextField()
# This is redundant as ques belongs to a test already
# test = models.ForeignKey('exam.Test')
I assume you want to get all the answers for one user and one test:
UserAnswer.objects.filter(
ques__test_id=test_id,
user_id=user_id
).values('ques_id', 'ques__ques', 'user_ans')

how to get chart's data and labels

I would like to represent my data in a form of a chart,
but i am having a problem making the right queries to display the chart's labels and series ,
and basically i have a Book model , and a User model
and i want to display the number of books(series) that belongs to a particular user(labels) .
models.by
class Book(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=200)
template_tag
#register.simple_tag()
def chart_data():
users =
books =
return json.dumps({
'labels':[user.username for user in users],
'series':[[book.name for book in books]]
})
Something like this:
users = User.objects.all()
for user in users:
books = Book.objects.filter(user=user)
If I understand correctly, You need a json data which should have a label represents username and series representing book.name for that particular user.
Have you tried :
books = Book.objects.values('user__username', 'name').order_by('user__username', 'name')
If you want to do it for a particular user, then:
series = Books.objects.filter(user = "username").values("name")
This will produce a queryset:
<queryset: [{name: book1}, {name: book2}, ...]>
You can convert it to list like so:
list(series)
and then send it through json.dumps..
In the above case, you already know the user those books belongs too, but if you want specify it through the query, then:
series = Books.objects.filter(user = "username").values("name", "user__username")
This will produce something like this:
<queryset: [{name: book1, user: username1}, {name: book2, user: username1}, ...]>

Creating unique index with peewee for table with foreign key

Say that I have a table called TBL_ACCOUNT which contains all of my users, and a table called TBL_EMAIL_SUBSCRIPTION where it contains the feeds that a user is subscribed to. I'm trying to make it so that there can only be one entry of each user+feed combination, so user1 can only be subscribed to feed1 once, but user1 can be subscribed to feed1 and feed2 simultaneously.
This is what my model looks like:
class TBL_ACCOUNT(BaseModel):
USERNAME = CharField(unique=True)
PASSWORD = CharField()
EMAIL = CharField(unique=True)
class TBL_EMAIL_SUBSCRIPTION(BaseModel):
USER = ForeignKeyField(TBL_ACCOUNT)
FEED = CharField()
class Meta:
indexes = (("USER_id", "FEED", True))
I have also tried just using "USER" for the indexes, but that didn't work out as the database still received duplicates.
Please refer to the peewee docs: http://docs.peewee-orm.com/en/latest/peewee/models.html#indexes-and-constraints
In your case it should look like this:
class Meta:
indexes = (
(("USER_id", "FEED"), True),
)
Note the use of commas! They are very important, because indexes are a tuple of tuples.

NDB query using filters on Structured property which is also repeated ?

I am creating a sample application storing user detail along with its class information.
Modal classes being used are :
Model class for saving user's class data
class MyData(ndb.Model):
subject = ndb.StringProperty()
teacher = ndb.StringProperty()
strength = ndb.IntegerProperty()
date = ndb.DateTimeProperty()
Model class for user
class MyUser(ndb.Model):
user_name = ndb.StringProperty()
email_id = ndb.StringProperty()
my_data = ndb.StructuredProperty(MyData, repeated = True)
I am able to successfully store data into the datastore and can also make simple query on the MyUser entity using some filters based on email_id and user_name.
But when I try to query MyUser result using filter on a property from the MyUser modal's Structured property that is my_data, its not giving correct result.
I think I am querying incorrectly.
Here is my query function
function to query based upon the repeated structure property
def queryMyUserWithStructuredPropertyFilter():
shail_users_query = MyUser.query(ndb.AND(MyUser.email_id == "napolean#gmail.com", MyUser.my_data.strength > 30))
shail_users_list = shail_users_query.fetch(10)
maindatalist=[]
for each_user in shail_users_list:
logging.info('NEW QUERY :: The user details are : %s %s'% (each_user.user_name, each_user.email_id))
# Class data
myData = each_user.my_data
for each_my_data in myData:
templist = [each_my_data.strength, str(each_my_data.date)]
maindatalist.append(templist)
logging.info('NEW QUERY :: The class data is : %s %s %s %s'% (each_my_data.subject, each_my_data.teacher, str(each_my_data.strength),str(each_my_data.date)))
return maindatalist
I want to fetch that entity with repeated Structured property (my_data) should be a list which has strength > 30.
Please help me in knowing where I am doing wrong.
Thanks.
Queries over StructuredProperties return objects for which at least one of the structured ones satisfies the conditions. If you want to filter those properties, you'll have to do it afterwards.
Something like this should do the trick:
def queryMyUserWithStructuredPropertyFilter():
shail_users_query = MyUser.query(MyUser.email_id == "napolean#gmail.com", MyUser.my_data.strength > 30)
shail_users_list = shail_users_query.fetch(10)
# Here, shail_users_list has at most 10 users with email being
# 'napolean#gmail.com' and at least one element in my_data
# with strength > 30
maindatalist = [
[[data.strength, str(data.date)] for data in user.my_data if data.strength > 30] for user in shail_users_list
]
# Now in maindatalist you have ONLY those my_data with strength > 30
return maindatalist

Categories

Resources