How to group list items by user - django

I have an object with foreign key Edp. A user can have several RespostaEdp as per the design. However, when printing the list I want to group them by user. Any ideas on how to get this done? I tried the solution below but I cannot access user values.
#teacher_required
def listarRespostasEDA(request):
edpsTodas = Edp.objects.all()
title = 'Estruturas Digitais Pedagogicas'
template = 'edp/listarEDArespondida.html'
edps = list()
for edp in edpsTodas:
if edp.respostas.all().count() != 0:
# if not edp.respostas.none:
edps.append(edp)
return render(request, template, {'title': title, 'edps': edps})
def listaAlunosResponderamEdp(request, slug):
edp = get_object_or_404(Edp, slug=slug)
# respostas = RespostaEdp.objects.filter(edp=edp)
lista = list()
respostas = RespostaEdp.objects.filter(edp=edp).values('aprendiz').distinct().order_by('aprendiz')
for r in respostas:
for k,v in r.items():
aluno = User.objects.filter(pk=v)
lista.append(aluno)
print (lista)
return render(request, 'edp/teste.html', {'lista':lista})
class RespostaEdp(models.Model):
edp = models.ForeignKey(Edp, verbose_name='Edp', related_name='respostas', on_delete=models.CASCADE)
video_embedded = EmbedVideoField(blank=True, null=True)
texto = models.TextField('Texto', blank=True)
video = models.FileField(upload_to='video/', storage=upload_storage, default="media/none.mp4")
aprendiz = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name='aluno', related_name='respostaAluno', on_delete=models.CASCADE)
# aprendiz = models.ForeignKey(Student, verbose_name='aprendiz ', related_name='respostaAprendiz', on_delete=models.CASCADE)
created_at = models.DateTimeField('Criado em', auto_now_add=True)
updated_at = models.DateTimeField('Atualizado em', auto_now=True)
def __str__(self):
return self.edp.titulo + " - " + self.aprendiz.username
def iniciar(self):
self.save()
#models.permalink
def get_absolute_url(self):
return ('edp:detalhe_edp_resposta', (), {'slug': self.slug})
class Meta:
verbose_name = 'Resposta Estrutura Digital de Aprendizagem'
verbose_name_plural = 'Resposta Estrutura Digital de Aprendizagem'
ordering = ['-created_at']
class User(AbstractUser):
eh_aluno = models.BooleanField(default=False)
eh_professor = models.BooleanField(default=False)
And here is the models of the users:
class User(AbstractUser):
eh_aluno = models.BooleanField(default=False)
eh_professor = models.BooleanField(default=False)
class Student(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
def __str__(self):
return self.user.username

Related

get() returned more than one Designated -- it returned 4

I am a student who is learning Django. You tried to insert the designated_code on Views.py, but the following error occurs: I don't know how to solve it at all. How can we solve this?
The element.designed_code part of join_create seems to be the problem.
I'd be really happy if you could help me solve the problem. I know that there are 4 products in the designated code, but I want to add the designated code that corresponds to the value of the selected value code.
Error:
get() returned more than one Designated -- it returned 4!
Models.py
class Value(models.Model):
value_code = models.AutoField(primary_key=True)
option_code = models.ForeignKey(Option, on_delete=models.CASCADE, db_column='option_code')
product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code')
name = models.CharField(max_length=32)
extra_cost = models.IntegerField()
def __str__(self):
return self.name
class Meta:
ordering = ['value_code']
class Designated(models.Model):
designated_code = models.AutoField(primary_key=True)
product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code')
price = models.IntegerField()
rep_price = models.BooleanField(default=True)
class Meta:
ordering = ['designated_code']
def __str__(self):
return str(self.designated_code)
class Element(models.Model):
element_code = models.AutoField(primary_key=True)
designated_code = models.ForeignKey(Designated, on_delete=models.CASCADE, db_column='designated_code')
value_code = models.ForeignKey(Value, on_delete=models.CASCADE, db_column='value_code', null=True, blank=True)
class Meta:
ordering = ['element_code']
def __str__(self):
return str(self.element_code)
class Join(models.Model):
join_code = models.AutoField(primary_key=True)
username = models.ForeignKey(Member, on_delete=models.CASCADE, db_column='username')
product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code')
part_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.join_code)
class Meta:
ordering = ['join_code']
Views.py
def join_create(request, id):
current_category = None
designated = Designated.objects.all()
designated_object = Designated.objects.filter(rep_price='True')
value_p = Value.extra_cost
element = Element.objects.all()
value_object = Value.objects.all()
categories = Category.objects.all()
products = Product.objects.all()
if not request.user.is_authenticated:
return HttpResponseRedirect(reverse('zeronine:login'))
if request.method == "POST":
product = Product.objects.get(product_code=id)
join = Join()
join.product_code = product
join.username = request.user
join.save()
if request.method == "POST":
form = ElementForm(request.POST)
if form.is_valid():
for value_code2 in request.POST.getlist('value_code2'):
element = Element()
element.designated_code = Designated.objects.get(product_code=id)
element.value_code = get_object_or_404(Value, pk=value_code2)
element.save()
else:
element = Element()
element.designated_code = Designated.objects.get(product_code=id)
element.value_code = None
element.save()
Forms.py
class ElementForm(forms.Form):
value_code2 = forms.ModelChoiceField(error_messages={'required': "옵션을 선택하세요."}, label="옵션", queryset=Value.objects.all())

How can i make a Query through Many-To-Many-Relationship

I want to display the trainer for a course date. A course can have several dates and a different trainer can be used on each date. A trainer can have a different role on each course date. (Instructor, helper...)
How do I make the correct query? Are the models correct for this?
Models:
class Course_dates(models.Model):
date = models.DateField()
start = models.TimeField()
end = models.TimeField()
def __str__(self):
return str(self.id)
"""return self.date.strftime("%d.%m.%Y")"""
class Course(models.Model):
course_number = models.CharField(max_length=24, blank=True)
course_location = models.ForeignKey(Course_location, on_delete=models.CASCADE)
course_dates = models.ManyToManyField('Course_dates', through="Course_Course_dates")
def __str__(self):
return self.course_number
class Trainer_Course_Course_date_role(models.Model):
trainer = models.ForeignKey(Trainer, on_delete=models.CASCADE)
role = models.CharField(max_length=24, blank=True)
def __str__(self):
return str(self.id)
class Course_Course_dates(models.Model):
course = models.ForeignKey(Course, on_delete=models.CASCADE)
course_dates = models.ForeignKey(Course_dates, on_delete=models.CASCADE)
trainer = models.ForeignKey(Trainer_Course_Course_date_role, on_delete=models.CASCADE, null=True)
def __str__(self):
return str(self.id)
class Trainer(models.Model):
salutation = models.CharField(max_length=8,choices=GENDER_CHOICES)
last_names = models.CharField(max_length=56)
first_names = models.CharField(max_length=56)
date_of_birth = models.DateField()
address = models.ForeignKey(Address, on_delete=models.CASCADE)
email = models.EmailField()
phone = models.CharField(max_length=56, blank=True)
mobile = models.CharField(max_length=56, blank=True)
def __str__(self):
return self.last_names
View:
def course(request):
courses = Course.objects.all()
course_list = []
for course in courses:
sorted_date_list = course.course_dates.all().order_by('date')
course_list.append({'course': course, 'sorted_date_list': sorted_date_list })
context = { 'course_list': course_list, }
return render(request, 'kursverwaltung_tenant/course.html', context)

Summing up total amount from multiple models in Django

The title of my question has said it all. I have multiple models, and I want to add up the amount to derive the total amount, here's my code
class FurnitureItem(models.Model):
fur_title = models.CharField(max_length=200)
fur_price = models.FloatField()
fur_discount_price = models.FloatField(blank=True, null=True)
fur_pictures = models.ImageField(upload_to='Pictures/', blank=True)
label = models.CharField(choices=LABEL_CHOICES, max_length=1)
category = models.CharField(choices=CATEGORIES_CHOICES, max_length=24)
fur_descriptions = models.TextField()
slug = models.SlugField()
date = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.fur_title
class FurnitureOrderItem(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
fur_ordered = models.BooleanField(default=False)
item = models.ForeignKey(FurnitureItem, on_delete=models.CASCADE)
quantity = models.IntegerField(default=1)
def __str__(self):
return f"{self.quantity} of {self.item.fur_title}"
....
def get_final_fur_price(self):
if self.item.fur_discount_price:
return self.get_total_discount_fur_price()
return self.get_total_item_fur_price()
class FurnitureOrder(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
fur_items = models.ManyToManyField(FurnitureOrderItem)
date_created = models.DateTimeField(auto_now_add=True)
ordered_created = models.DateTimeField()
fur_ordered = models.BooleanField(default=False)
def __str__(self):
return self.user.username
def get_total_fur_everything(self):
total = 0
for fur_order_item in self.fur_items.all():
total += fur_order_item.get_final_fur_price()
return total
class GraphicItem(models.Model):
graphic_title = models.CharField(max_length=200)
graphic_price = models.FloatField()
graphic_discount_price = models.FloatField(blank=True, null=True)
graphic_pictures = models.ImageField(upload_to='Pictures/', blank=True)
label = models.CharField(choices=LABEL_CHOICES, max_length=1)
category = models.CharField(choices=CATEGORIES_CHOICES, max_length=24)
graphic_descriptions = models.TextField()
slug = models.SlugField()
date = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.graphic_title
class GraphicOrderItem(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
graphic_ordered = models.BooleanField(default=False)
item = models.ForeignKey(GraphicItem, on_delete=models.CASCADE)
quantity = models.IntegerField(default=1)
def __str__(self):
return f"{self.quantity} of {self.item.graphic_title}"
....
def get_final_graphic_price(self):
if self.item.graphic_discount_price:
return self.get_total_discount_graphic_price()
return self.get_total_item_graphic_price()
class GraphicOrder(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
graphic_items = models.ManyToManyField(GraphicOrderItem)
date_created = models.DateTimeField(auto_now_add=True)
ordered_created = models.DateTimeField()
graphic_ordered = models.BooleanField(default=False)
def __str__(self):
return self.user.username
def get_total_graphic_everything(self):
total = 0
for graphic_order_item in self.graphic_items.all():
total += graphic_order_item.get_final_graphic_price()
return total
what i've tried as regards summing up the amount for furniture and graphics
class TotalAmount(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
graphic_items = models.ManyToManyField(GraphicOrderItem)
fur_items = models.ManyToManyField(FurnitureOrderItem)
date_created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.user.username
def amount(self):
return self.graphic_items.get_total_graphic_everything() + self.fur_items.get_total_fur_everything()
Then my views goes this way:
class Summary(LoginRequiredMixin, View):
def get(self, *args, **kwargs):
try:
fur_order = FurnitureOrder.objects.get(user=self.request.user, fur_ordered=False)
graphic_order = GraphicOrder.objects.get(user=self.request.user, graphic_ordered=False)
amount = TotalAmount.objects.get(user=self.request.user)
context = {
'fur_order':fur_order,'graphic_order':graphic_order,'amount':amount}
return render(self.request, 'business/home-order-summary.html', context)
Thanks for your time, I no the code is lengthy, but I wanted to expanciate better.

Two Django models with foreign keys in one view

I'm starting with Django. I have 3 models, a parent class "Cliente" and two child classes, "Persona" and "Empresa".
models.py
class Cliente(models.Model):
idcliente = models.AutoField(unique=True, primary_key=True)
direccion = models.CharField(max_length=45L, blank=True)
telefono = models.CharField(max_length=45L, blank=True)
email = models.CharField(max_length=45L, blank=True)
def __unicode__(self):
return u'Id: %s' % (self.idcliente)
class Meta:
db_table = 'cliente'
class Empresa(models.Model):
idcliente = models.ForeignKey('Cliente', db_column='idcliente', primary_key=True)
cuit = models.CharField(max_length=45L)
nombre = models.CharField(max_length=60L)
numero_ingresos_brutos = models.CharField(max_length=45L, blank=True)
razon_social = models.CharField(max_length=45L, blank=True)
def __unicode__(self):
return u'CUIT: %s - Nombre: %s' % (self.cuit, self.nombre)
class Meta:
db_table = 'empresa'
class Persona(models.Model):
idcliente = models.ForeignKey('Cliente', db_column='idcliente', primary_key=True)
representante_de = models.ForeignKey('Empresa', null=True, db_column='representante_de', blank=True, related_name='representa_a')
nombre = models.CharField(max_length=45L)
apellido = models.CharField(max_length=45L)
def __unicode__(self):
return u'Id: %s - Nombre completo: %s %s' % (self.idcliente, self.nombre, self.apellido)
class Meta:
db_table = 'persona'
I want to manage a class and its parent in the same view. I want to add, edit and delete "Cliente" and "Persona"/"Cliente" in the same form. Can you help me?
There is a good example in the Documentation Here.
I wrote this based on the documentation, so it is untested.
def manage_books(request, client_id):
client = Cliente.objects.get(pk=client_id)
EmpresaInlineFormSet = inlineformset_factory(Cliente, Empresa)
if request.method == "POST":
formset = EmpresaInlineFormSet(request.POST, request.FILES, instance=author)
if formset.is_valid():
formset.save()
# Do something. Should generally end with a redirect. For example:
return HttpResponseRedirect(client.get_absolute_url())
else:
formset = EmpresaInlineFormSet(instance=client)
return render_to_response("manage_empresa.html", {
"formset": formset,
})

django ManyToManyField show slug as label

i have a "rare" behavior here, i this model:
models.py
class Area(models.Model):
area = models.CharField(max_length=150,unique=True)
slug = models.SlugField(max_length=200)
fecha = models.DateTimeField(default=datetime.date.today,editable=False)
activa = models.BooleanField(default=True)
class Empresa(models.Model):
usuario = models.ForeignKey(User)
nombre = models.CharField(max_length=150)
telefono = models.CharField(max_length=20)
fax = models.CharField(max_length=20,null=True,blank=True)
actividad = models.ManyToManyField(Area)
I dont know why the m2m_field actividad, into the django admin and any forms html is showing the slug field from the model Area as label
i was just returning the slug field and not the area "name"
class Area(models.Model):
area = models.CharField(max_length=150,unique=True)
slug = models.SlugField(max_length=200)
fecha = models.DateTimeField(default=datetime.date.today,editable=False)
activa = models.BooleanField(default=True)
def __unicode__(self):
return self.area # was self.slug
def get_absolute_url(self):
return '/areas/%s' % self.slug