I am trying to understand how exactly query works on Django, i followed the tutorials it´s not working I am not sure what i am doing wrong.
When I run
BeneficientePagar.objects.filter(nome__contains="Joao Pedro")
it returns
"Choices are %s" %s (name, ",".join(available))) django.core.exceptions.FieldError: Cannot resolve keyword "nome into field. Choices are: ID, beneficiente, beneficiente_id,join, join_id, moeda
from django.db import models
# Create your models here.
class Moeda(models.Model):
moeda_ficticia = models.FloatField()
class Join(models.Model):
nome = models.CharField(max_length=150)
nascimento = models.DateField()
cpf = models.IntegerField(primary_key=True)
endereco = models.CharField(max_length=150)
email = models.EmailField()
def __str__(self):
return self.nome
class Beneficiente(models.Model):
ID = models.AutoField(primary_key=True)
nome = models.CharField(max_length=150)
CNPJ = models.IntegerField(max_length = 10)
def __str__(self):
return self.nome
class Favores(models.Model):
ID = models.AutoField(primary_key=True)
favor = models.CharField(max_length=150)
dataInserido = models.DateField()
usuarios = models.ForeignKey(Join)
def __str__(self):
return self.favor
class BeneficientePagar(models.Model):
ID = models.AutoField(primary_key=True)
moeda = models.IntegerField()
beneficiente = models.ForeignKey(Beneficiente)
join = models.ForeignKey(Join)
def __str__(self):
return self.ID
Thanks in advance
If using BeneficientPager, you need to do
BeneficientePagar.objects.filter(beneficient__nome__contains="Joao Pedro")
You are getting the error because nome is a field on Beneficiente, not BeneficientePagar.
You can either do
Beneficiente.objects.filter(nome__contains="Joao Pedro")
which will return a queryset of Beneficientes. Or if you need BeneficientePagar you can query through the foreign key.
BeneficientePagar.objects.filter(beneficiente__nome__contains="Joao Pedro")
Related
I'm trying to duplicate multiple data I only need to change their related foreignkeymy problem is that I'm able to duplicate but with the same foreignkey below is my code
any suggestions please
from django.db import models
class Category(models.Model):
category_name = models.CharField(max_length=100)
def __str__(self):
return self.category_name
class Client(models.Model):
cat = models.ForeignKey(Category, on_delete=models.CASCADE, null=True, blank=True)
fname = models.CharField(max_length=100)
lname = models.CharField(max_length=100)
age = models.IntegerField()
married = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.fname + " " + self.lname + " " + str(self.cat)
def show_category(request, cat_id):
clients = Client.objects.filter(cat__id=cat_id)
if request.method =='POST':
for i in clients:
i.id = None
i.cat.id=3
i.save()
return redirect('/')
context = {'clients':clients}
return render(request, 'app/home_cat.html', context)
See the documentation on copying model instances:
def change_category(clients, new_category_id):
for client in clients:
client.pk = None
client._state.adding = True
client.cat_id = new_category_id
client.save()
I am trying to write a year level filter for my student profile list, however, the query returns an empty [].
This is my Attendance model, manager and custom queryset:
class AttendanceQuerySet(models.QuerySet):
def get_yearlevel(self, yearlevel):
return self.filter(BCEID__YearLevel = yearlevel)
class AttendanceManager(models.Manager):
def get_queryset(self):
return AttendanceQuerySet(self.model, using=self._db)
def get_yearlevel(self, yearlevel):
return self.get_queryset().get_yearlevel(yearlevel)
class Attendance(models.Model):
BCEID = models.OneToOneField(StudentProfile,primary_key=True,on_delete=models.CASCADE)
AttendanceRate = models.CharField(max_length=10)
objects = AttendanceManager()
def __unicode__(self):
return self.BCEID
StudentProfile model:
class StudentProfile(models.Model):
RelatedPersonName = models.CharField(max_length=10)
RelatedPersonFirstName = models.CharField(max_length=30)
RelatedPersonFamName = models.CharField(max_length=30)
StudentLegalName = models.CharField(max_length=30)
StudentFamName = models.CharField(max_length=30)
Email = models.CharField(max_length=130)
Street1 = models.TextField(max_length=30)
Suburb = models.CharField(max_length=30)
State = models.CharField(max_length=5)
PostCode = models.CharField(max_length=6)
StudentLegalName = models.CharField(max_length=30)
StudentFamName = models.CharField(max_length=30)
StudentNo = models.CharField(primary_key=True,max_length=10)
Class = models.CharField(max_length=6)
YearLevel = models.CharField(max_length=10)
objects = StudentProfileManager()
def __unicode__(self):
return self.StudentNo
and AttendanceListView (views.py)
class AttendanceListView(ListView):
model = Attendance
queryset = Attendance.objects.get_yearlevel("Year 8")
I manually queried the database to check if there were errors in my code, and got the same result: an empty array [].
SQL:
SELECT "student_attendance"."BCEID_id",
"student_attendance"."AttendanceRate"
FROM "student_attendance"
INNER JOIN "student_studentprofile"
ON ("student_attendance"."BCEID_id" = "student_studentprofile"."StudentNo")
WHERE "student_studentprofile"."YearLevel" = 'Year 8'
Please let me know what I am doing wrong here.
I would like to filter my plots objects on the fruit ex.pear. The Inputs are linked via a manytomany to the plots. This is the structure:
This is the data I get out of it:
What i would like to have:
result:
I tried the following:
plots = Plot.objects.filter(fruittype__fruit="Pear")
inputs = Input.objects.filter(plot__in=plots).distinct()
This gives me already a close solution for my problem but not what I want.
Now I only would like to filter out the other plots that still show up with apple.
models inputs:
class Product (models.Model):
type = models.ForeignKey(Type, on_delete=models.CASCADE)
product = models.CharField(max_length=70)
standaard_dosis = models.FloatField()
def __str__(self):
return self.product
class Input (models.Model):
datum = models.DateField()
plot = models.ManyToManyField(Plot)
def __str__(self):
return str(self.datum)
class ProductInputs (models.Model):
input = models.ForeignKey(Inputs, on_delete=models.CASCADE, default="")
product = models.ForeignKey(Product, on_delete=models.CASCADE, default="")
dosis = models.FloatField()
def __str__(self):
string = str(self.product)
return string
models plots:
class Fruit(models.Model):
fruit = models.CharField(max_length=30, primary_key=True)
def __str__(self):
return self.fruit
class Meta:
verbose_name_plural = "fruits"
class Fruittype(models.Model):
fruit = models.ForeignKey(Fruit, on_delete=models.CASCADE)
fruittype = models.CharField(max_length=30, primary_key=True)
def __str__(self):
return self.fruittype
class Meta:
verbose_name_plural = "fruitypes"
class Plot(models.Model):
name = models.CharField(max_length=30)
fruittype = models.ForeignKey(Fruittype, on_delete=models.CASCADE)
def __str__(self):
return str(self.fruittype.fruit) + " | " + self.name
class Meta:
verbose_name_plural = "plots"
Your Plot queryset is not going as deep as it should. I think you should change to something like this (although this is it's a bit of overkill)
plot_ids = Plot.objects.filter(fruittype__fruit__fruit="Pear").values_list('pk', flat=True)
or
plot_ids = Plot.objects.filter(fruittype__fruittype="Pear").values_list('pk', flat=True) # I don't know what fruittype is but I guess this would help you
Then your "inputs"
inputs = Input.objects.filter(plot__pk__in=plot_ids).distinct()
You might wanna try this as well:
from django.db.models import Prefetch
Input.objects.prefetch_related(
Prefetch('plot', queryset=Plot.objects.filter(fruittype__fruit__fruit="Pear"))
)
It worked with:
all_inputs=Input.objects.filter(plot__pk__in=plot_ids).distinct().prefetch_related(Prefetch('plot', queryset=Plot.objects.filter(fruittype__fruit__fruit="Pear")))
I am a beginner in django. Following is my Attendance Management App.
This is my models.py.
from django.db import models
class Subject(models.Model):
subject_name = models.CharField(max_length=20)
#attendance = models.ForeignKey(Attendance, on_delete =
models.DO_NOTHING)
attendance = models.IntegerField(default=0)
def __str__(self):
return self.subject_name
class Section(models.Model):
section_name = models.CharField(max_length=20)
subject = models.ManyToManyField(Subject)
def __str__(self):
return self.section_name
class Student(models.Model):
rollno = models.IntegerField()
name = models.CharField(max_length=20)
section = models.ForeignKey(Section, on_delete = models.DO_NOTHING,
default=0)
def __str__(self):
return str(self.rollno) + self.name
class Teacher(models.Model):
#teacher_name = models.CharField(max_length=20)
section = models.ForeignKey(Section, on_delete=models.CASCADE)
subject = models.ForeignKey(Subject, on_delete=models.CASCADE)
#section_name = models.CharField(max_length=10)
#subject_name = models.CharField(max_length=30)
def __str__(self):
return self.section.section_name+' '+self.subject.subject_name
class TeacherList(models.Model):
teacher_name = models.CharField(max_length=20)
teacher = models.ManyToManyField(Teacher)
def __str__(self):
return self.teacher_name
The line below is not working in views.py
student = models.Student.objects.get(rollno = sroll)
student.section.subject.get(subject_name = 'java').attendance += 1
student.save()
This view is called from a template when a button is clicked to add attendance of a student.
The attendance in above code is not modified. Please help me out.
You're saving the student, instead of the subject.
student = models.Student.objects.get(rollno = sroll)
subject = student.section.subject.get(subject_name='java')
subject.attendance += 1
subject.save()
Or, better, do the update directly in one go:
student.section.subject.filter(subject_name='java').update(attendance=F('attendance')+1)
and there's no need to save at all.
Hello i'm studying django, and
i have a problem with def str on models
models.py
class Student(models.Model):
id = models.AutoField(primary_key=True)
school_year = models.CharField(max_length=4,choices=SCHOOL_YEAR_CHOICES,default='2019')
campus = models.CharField(max_length=1,choices=CAMPUS_CHOICES,default='M')
type = models.CharField(max_length=1,choices=TYPE_CHOICES,default='N')
affiliate = models.CharField(max_length=1,choices=AFFILIATE_CHOICES,default='N')
name = models.CharField(max_length=30, unique=True)
def __str__(self):
return self.name,self.campus
class Comment(models.Model):
student = models.ForeignKey(Student, related_name='comments',on_delete=models.CASCADE)
created_by = models.ForeignKey(User,related_name='comments',on_delete=models.CASCADE)
message = models.TextField(max_length=1000, unique=False)
about = models.CharField(max_length=1,choices=ABOUT_CHOICES,default='L')
created_at = models.DateTimeField(auto_now_add = True)
updated_at = models.DateTimeField(auto_now = True)
def __str__(self):
return self.created_by.first_name, self.student.name
if i remove that " student = models.ForeignKey ~~" on class Comment, it'll work
i think 'student' on class comment makes a problem
anyone help? thanks
and i'm using python3 with the lastest version of django
Use this on Comment model:
def __str__(self):
return self.created_by.first_name + ' ' + self.student.name
Also on Student model:
def __str__(self):
return self.name + ' ' + self.campus
Redefine __str__:
def __str__(self):
return self.name+' '+self.campus