How can I ask questions randomly to different user in django? - html

I want to create a list of questions and from it I want to ask random 5 questions
to each logged in user.How can i do it. where can I create a list of quetions
and options.How can I render questions and answer to html page ?
I tried to create a db table and used it to get values in html template
But it did not work.
class Quetions(models.Model):
quetion =models.CharField(max_length=100,default='')
option1=models.CharField(max_length=20,default='')
option2=models.CharField(max_length=20,default='')
option3=models.CharField(max_length=20,default='')
option4 =models.CharField(max_length=20, default='')

While fetching the question, you can do something like
pks = Quetions.objects.values_list('pk', flat=True)
random_idx = random.sample(range(0, len(pks)-1), 5)
random_questions = Quetions.objects.filter(pk__in=random_idx)

Related

Contao CMS Query a 'checkboxWizard' BLOB field

I have a question about how to query a 'checkboxWizard' BLOB field. In have added a such field to tl_member. This is working very fine. I can add “0 to N” selection to each members. Let’s call this field “myBlob”.
Now the questions is how to query “myBlob” with the Contao way? Let’s say I want all member that are in the postal code “12120” and that have the id “2” of “myBlob” selected. Not only “2” but at least this one.
$arrColumn[] = "tl_member.postal=?";
$arrValues[] = 12120;
$arrColumn[] = "tl_member.myBlob=?"; <- how to say “contains in the blob” here?
$arrValues[] = 2;
self::findBy($arrColumn, $arrValues)
The only way to do this (when using the default Contao method for such relationships) is to create a query like:
… WHERE myBlob LIKE '%"2"%'
So in your case it might be:
$arrColumn[] = "tl_member.myBlob LIKE ?";
$arrValues[] = '%"2"%';
However, this is of course cumbersome and might not work in all cases.
May be a better way would be to use codefog/contao-haste with its 'many to many' helper: https://github.com/codefog/contao-haste/blob/master/docs/Model/index.md
This way you will have a separate table containing the references.

How to store and display with HTML m:n array(two dimensional table)

How to organize information(in MVC model) in order to represent this real example:
Survey - can have multiple questions and multiple people who will answer them
Question - only single answer - yes or no
PersonAnswer - the one that answer the question
Sample display:
My implementation so far is:
DB
Survey - Question - one to many
Question - PersonAnswer - one to many
controller code: - pseudo code
Survey.FindAllQuestions
Loop per each Question and find all answers
result is map - Survey = [Question1: AnswerList1, Question2: AnswerList2]
In the HTML looping over the map I'm able to diplay the information
Problems of my approach:
the header - people names should be calculated
sort of the lists is needed otherwise the answers will be mixed
How to manage properly if the person didn't answer a question - should I store it in the database?
Update: I'm using java and mysql.
My approach to this question would first deal with the database:
In my case this is how i would do it:
Have a table of
users->represents db users
surveyitems->with item(questions) and id(probaby autoincrement integer pkey),
surveycheks->representing the users and their checks having({
id(pkey),
checkid(foreign_key ->to surveyitems table id)
yeschecked(representing the yes)
nochecked(representi)ng the nos
})
Then in your views eg when using yii php framework
use gii tool to generate models and crud //here you can use your own
logic of saving data to db
On your survey form
1. load all surveys from table surveyitems with id and items()// display item
2. Have radio buttons with values of id(from survey items);
3.. when saving loop through all checked yes or nos and store them in surveycheks
I hope you get the idea

Django GenereicForeignKey v/s custom manual fields performance/optimization

I'm trying to build a typical social networking site. there are two types of objects mainly.
photo
status
a user can like photo and status. (Note that these two are mutually exclusive)
means, We have two table (1) for Image only and other for status only.
now when a user likes an object(it could be a photo or status) how should I store that info.
I want to design a efficient SQL schema for this.
Currently I'm using Genericforeignkey(GFK)
class LikedObject(models.Model):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
but yesterday I thought if I can do this without using GFK efficiently?
class LikedObject(models.Model):
OBJECT_TYPE = (
('status', 'Status'),
('image', 'Image/Photo'),
)
user = models.ForeignKey(User, related_name="liked_objects")
obj_id = models.PositiveIntegerField()
obj_type = models.CharField(max_length=63, choices=OBJECT_TYPE)
the only difference I can understand is that I have to make two queries if I want to get all liked_status of a particular user
status_ids = LikedObject.objects.filter(user=user_obj, obj_type='status').values_list('object_id', flat=True)
status_objs = Status.objects.filter(id__in=status_ids)
Am I correct? so What would be the best approach in terms of easy querying/inserting or performance, etc.
You are basically implementing your own Generic Object, only you limit your ContentType to your hard coded OBJECT_TYPE.
If you are only going to access the database as in your example (get all status objects liked by user x), or a couple specific queries, then your own implementation can be a little faster, of course. But obviously, if later you have to add more objects, or do other things, you may find yourself implementing your whole full generic solution. And like they say, why reinvent the wheel.
If you want better performance, and really only have those two Models to worry about, you may just want to have two different Like tables (StatusLike and ImageLike) and use inheritance to share functionality.
class LikedObject(models.Model):
common_field = ...
class Meta:
abstract = True
def some_share_function():
...
class StatusLikeObject(LikedObject):
user = models.ForeignKey(User, related_name="status_liked_objects")
status = models.ForeignKey(Status, related_name="liked_objects")
class ImageLikeObject(LikedObject):
user = models.ForeignKey(User, related_name="image_liked_objects")
image = models.ForeignKey(Image, related_name="liked_objects")
Basically, either you have a lot of Models to worry about, and then you probably want to use the more Django generic object implementation, or you only have two models, and why even bother with a half generic solution. Just use two tables.
In this case, I would check if your data objects Status and Photo may have many common data fields, e.g. Status.user and Photo.user, Status.title and Photo.title, Status.pub_date and Photo.pub_date, Status.text and Photo.caption, etc.
Could you combine them into an Item object maybe? That Item would have a Item.type field, either "photo" or "status"? Then you would only have a single table and a single object type a user can "like". Much simpler at basically no cost.
Edit:
from django.db import models
from django.utils.timezone import now
class Item(models.Model):
data_type = models.SmallIntegerField(
choices=((1, 'Status'), (2, 'Photo')), default=1)
user = models.ForeignKey(User)
title = models.CharField(max_length=100)
pub_date = models.DateTimeField(default=now)
...etc...
class Like(models.Model):
user = models.ForeignKey(User, related_name="liked_objects")
item = models.ForeignKey(Item)

sqlalchemy relations and query on relations

Suppose I have 3 tables in sqlalchemy. Users, Roles and UserRoles defined in declarative way. How would one suggest on doing something like this:
user = Users.query.get(1) # get user with id = 1
user_roles = user.roles.query.limit(10).all()
Currently, if I want to get the user roles I have to query any of the 3 tables and perform the joins in order to get the expected results. Calling directly user.roles brings a list of items that I cannot filter or limit so it's not very helpful. Joining things is not very helpful either since I'm trying to make a rest interface with requests such as:
localhost/users/1/roles so just by that query I need to be able to do Users.query.get(1).roles.limit(10) etc etc which really should 'smart up' my rest interface without too much bloated code and if conditionals and without having to know which table to join on what. Users model already has the roles as a relationship property so why can't I simply query on a relationship property like I do with normal models?
Simply use Dynamic Relationship Loaders. Code below verbatim from the documentation linked to above:
class User(Base):
__tablename__ = 'user'
posts = relationship(Post, lazy="dynamic")
jack = session.query(User).get(id)
# filter Jack's blog posts
posts = jack.posts.filter(Post.headline=='this is a post')
# apply array slices
posts = jack.posts[5:20]

How to maintain duplicate record in database?

My table contains two columns Title and Description.
I want to provide a functionality to user to create duplicate page for existing page.
Like for existing page database store value like.
Title1 , Description1
When user clicks on duplicate page button I want to create a duplicate entry for the existing page like this.
1) Click First Time
Copy_1_Title1,
Description1
2) Click Second Time
Copy_2_Title1,
Description1
How can I create this type of functionality ? How should be my database for this ? Is this a proper way ?
I think you should create third column and name it for example copy_number, and then before creating record you can find it by title and if title exist you can get value of copy_number and increment it. Then you can use this number to display titles as you wish:
"copy_#{record.copy_number}_#{record.title}" or something like this.
#bor1s has suggested very right solution.
But for the interest you can use this mthod for duplication :)
class Page < AR::Base
def duplicate
# new_page = self.clone
new_page = Page.new self.attributes.except(:id, :created_at, :updated_at)
copy = (self.title.match(/Copy_(\d)+.*/).try([1]) || 0) + 1
new_page.title = "Copy_#{copy}_#{self.title}"
new_page.save
end
end