Counting Boolean Values in field of Child Model in Django QuerySet API - python

I have the following model (below).
I would like a query that returns every record of parent Question(models.Model), where ALL the values for the is_relevant field within the child Choice(models.Model) are "True".
Having a difficult time creating the QuerySet. Any Assistance would be very helpful.
model.py
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
is_relevant = models.BooleanField()

You can use the reverse relationship of the Question model like so:
Question.objects.filter(choice__is_relevant=True)
The choice in choice__is_relevant is the lowercase name of the model Choice.
Reference: Relationship lookups

Related

Django ForeignKey.limit_choices_to with ForeignKey to ManyToMany scenario

I have a complex relation scenario as shown below. I'd like limit_choices_to Questions that are related to JobChecklistAnswer.job_checklist.checklist on JobChecklistAnswer.question.
How can I filter those Questions as Q object (or callable as the docs say)?
class Checklist(models.Model):
name = models.CharField(_("name"), max_length=150)
description = models.CharField(_("description"), max_length=150)
class Question(models.Model):
checklist = models.ForeignKey(Checklist, on_delete=models.CASCADE)
question = models.CharField(_("question"), max_length=200)
class Job(models.Model):
...
...
class JobChecklist(models.Model):
job = models.ForeignKey(Job, on_delete=models.CASCADE)
checklist = models.ForeignKey(Checklist, on_delete=models.CASCADE)
class JobChecklistAnswer(models.Model):
job_checklist = models.ForeignKey(JobChecklist, on_delete=models.CASCADE)
# FIXME: Add limit_choices_to query question
question = models.OneToOneField(ChecklistItem, on_delete=models.CASCADE)
answer = models.TextField(_("answer"))
In contrast to the OneToOneField "reverse" relation, a ForeignKey "reverse" relation returns a QuerySet.
You are not returning a queryset here in the OneToOneField, You are only reversing a relation between them
So the first step is to change OneToOneField into a ForeignKey
then you can use limit_choices_to attribute on ForeignKey

How Can I Associate A Foreign Key Of A Django Class Model Field To A Parent's Class Field

I am creating a question and answer django model where i want to set the correct answer to an option on the same class
Essentially I Want To Do Something Like This
class Question(models.Model):
question = models.CharField(max_length=40)
options = models.ManyToManyField('Answer')
correct_answer = models.ForeignKey('self.options',on_delete=models.CASCADE)
Unfortunately I'm Getting Errors From Django.
Why don't you just point the foreign key to the same model? Like this:
class Question(models.Model):
question = models.CharField(max_length=40)
options = models.ManyToManyField('Answer')
correct_answer = models.ForeignKey('Answer',on_delete=models.CASCADE)

How should I give ForeignKey to model?

How should I give ForeignKey to model?
Now models.py has User&Item table like
from django.db import models
# Create your models here.
class User(models.Model):
user_id = models.CharField(max_length=200)
name_id = models.CharField(max_length=200)
regist_date = models.DateTimeField(auto_now=True)
class Item(models.Model):
user_id = models.CharField(max_length=200)
name = models.CharField(max_length=200)
item_name = models.CharField(max_length=200)
price = models.CharField(max_length=200)
I wanna treat user_id&name_id as Foreing key.User table is parent table,and Item is child one.I think user_id&name_id in Item should have ForeignKey like
class Item(models.Model):
user_id = models.ForeignKey()
name = models.ForeignKey()
However,how should I connect these 2 model is User is parent&Item is child ?How should I write it?
For sure, you have to read that.
Looks like One User -> Many Items.
Its ForeignKey and we have to set it in User model.
class Item(models.Model):
...
class User(models.Model):
...
item = models.ForeignKey(Item)
You can use something like
class Item(models.Model):
user = models.ForeignKey(User, related_name='items')
Accessing user_id from item will be
item.user.user_id
Accessing all items from a user will be
user.items.all()
It's a good idea to read the documentation on the ForeignKey field.
As for your question, you can connect the Item model to the User model like this:
class Item(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
Again, it's a good idea to read the documentation and figure out what exactly you need, such as what to do when a User object is deleted (the on_delete part in my code).

Setting up default ForeignKey in django models

I need to set up default Foreign Key for a model at the model declaration stage (in models.py). I use the following code:
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return str(self.pub_date)
def create_question():
q=Question(question_text='default text', pub_date=datetime.now())
q.save()
return q.id
class Choice(models.Model):
question = models.ForeignKey(Question, default=lambda: create_question())
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
This works fine, the Choice instance and associated Question instance are created... But saving of Choice instance leads to creation of two additional (useless) Question instances. It seems like that default-lambda is called several times during Choice instance saving. I don't need these additional Question instances. How to avoid their creation?
NOTE: In python-shell everything works well:
c=Choice(votes=5, choice_text='dim')
c.save()
creates one instance of Choice and one associated instance of Question. Only using admin save button leads to extra Question instances creation!

Django Help: AttributeError: 'module' object has no attribute 'Charfield'

I have seen several similar posts of other attributes found but not this. New to Python and Django- I've done the first part of the several tutorials including Django's "Polls" tutorial and when it gets to the point where I syncdb for my app I invariably get 'AttributeError: 'module' object has no attribute CharField.
In models I have copied exactly as the tutorial says:
from django.db import models
class Poll(models.Model):
question = models.Charfield(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
# Create your models here.
'polls' is also added to installed apps and I'm using sqlite3, windows 7, python 2.7.
Any help very appreciated! (I'm trying very hard to learn!)
That is CharField, with uppercase 'f', and not Charfield as in your code.
I think in forms.py you are using
from django.forms import forms
Please use this
from django import forms
change charfield to:
CharField(max_length = 10)
both C and F should be capitalized
This :
question = models.CharField(max_length=200)
Instead of :
question = models.Charfield(max_length=200)
I have the same error but following code works for me:
from django.db import models
#Create your models here.
class Question(models.Model):
question_text = models.CharField(max_length=100)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
choice_text = models.CharField(max_length = 200)
votes = models.IntegerField(default =0)
question = models.ForeignKey(Question, on_delete=models.CASCADE)
Simply change charfield() to charField() ..
In model Poll, spelling of CharField is not properly formatted. Ie you have written a small letter f inplace of a capital letter F. So, replace Charfield by CharField. You can see the code below:
from django.db import models
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published') class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
Use this
from django.db import models

Categories