Trying to fetch a function from a table that is supposed to be there, but cannot get the value. Trying to get the amount of task that is completed.
models.py
class Task(models.Model):
title = models.CharField(max_length=55, null=True, blank=True)
slug = models.SlugField(max_length=500, unique=True, blank=True)
task_completed = models.BooleanField(default=False)
description = models.TextField(default="Task description")
start_date = models.DateTimeField()
due_date = models.DateTimeField()
checklist = models.ManyToManyField(Checklist, blank=True)
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
super(Task, self).save(*args, **kwargs)
def get_url(self):
return reverse('checklists', kwargs={
'slug':self.slug
})
def __str__(self):
return self.title
#property
def num_task_completed(self):
return self.task_completed.count()
class Project(models.Model):
project_manager = models.ForeignKey(Profile, on_delete=CASCADE)
title = models.CharField(max_length=55, null=True, blank=True)
developers = models.ManyToManyField(Profile, related_name='projects')
slug = models.SlugField(max_length=500, unique=True, blank=True)
description = models.TextField(default="Project description")
date = models.DateTimeField(auto_now_add=True)
start_date = models.DateTimeField()
due_date = models.DateTimeField()
tasks = models.ManyToManyField(Task, blank=True)
teams = models.ManyToManyField(Team, blank=True)
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
super(Project, self).save(*args, **kwargs)
def get_url(self):
return reverse('project_detail', kwargs={
'slug':self.slug
})
def __str__(self):
return self.title
#property
def num_task(self):
return self.tasks.count()
Then in the html is just loop through all projects
{% for projects in projects.all %}
<span class="text-small"> {{ projects.tasks.num_task_completed }} /{{ projects.num_task }}</span>
I manage to get the amount of tasks, but not the amount completed.
Use self.tasks.filter(task_completed = True).count() to get the number of completed tasks in a project.
Related
**Please can someone assist what I am not doing right. I want to upload data via CSV with the model below. I keep getting this error - AttributeError: 'str' object has no attribute 'strftime' whenever I want to upload via csv. I try to create a form with the same model and it worked. **attached is the error response
model.py
from MySQLdb import TIME
from django.db import models
from django.contrib.auth.models import User
from datetime import date, datetime, time, timedelta
import datetime
from django.db.models import F
class CustomManager(models.Manager):
def custom_update_or_create(self,*args, **kwargs):
start_time_value = kwargs.pop('start_time', None)
if start_time_value:
kwargs['start_time'] = self.get_date_value(start_time_value)
stop_time_value = kwargs.pop('stop_time', None)
if stop_time_value:
kwargs['stop_time'] = self.get_date_value(stop_time_value)
return super(CustomManager, self).update_or_create(*args, **kwargs)
def get_date_value(self, value):
input_formats = [
'%H:%M',
'%H:%M:%S',
'%I:%M:%S %P'
]
for format in input_formats:
try:
return self.strptime(value, format)
except (ValueError, TypeError):
continue
def strptime(self, value, format):
return datetime.datetime.strptime(value, format)
class Schedule(models.Model):
id = models.BigAutoField(primary_key=True )
avayaid = models.IntegerField()
username= models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True )
first_name = models.CharField(max_length=30, null=True, blank=True)
last_name = models.CharField(max_length=30, null=True, blank=True)
emp_id = models.CharField(max_length=30, null=True, blank=True)
team = models.ForeignKey(CCTeam, on_delete=models.SET_NULL, null=True, blank=True)
workcode = models.ForeignKey(WorkCode, on_delete=models.SET_NULL, null=True, blank=True )
new_week = models.CharField(max_length=10, null=True, blank=True)
day_of_week = models.CharField(max_length=10, null=True, blank=True)
start_date = models.DateField(auto_now=False, auto_now_add=False, default = date.today)
start_time = models.TimeField(auto_now=False, auto_now_add=False, null=True, blank=True)
stop_date = models.DateField(auto_now=False, auto_now_add=False, default=date.today)
stop_time = models.TimeField(auto_now=False, auto_now_add=False, null=True, blank=True)
duration = models.DurationField(null=True, blank=True)
workref = models.CharField(max_length=30, blank=True, null=True)
Memo = models.CharField(max_length=120, blank=True, null=True)
created_by = models.CharField(max_length=50, null=True, blank=True)
modified_by = models.CharField(max_length=50, null=True, blank=True)
created_on = models.DateTimeField(auto_now_add=True)
Modified_on = models.DateTimeField(auto_now=True)
objects = CustomManager()
def save(self, *args, **kwargs):
self.day_of_week=self.start_date.strftime('%A')
my_date = self.start_date # if date is 01/01/2018
year, week_num, day_of_week = my_date.isocalendar()
print("Week #" + str(week_num) + " of year " + str(year) + " of Day of the week " + str(day_of_week))
self.new_week = week_num
return super().save(*args, **kwargs)
view.py
def schedule_bulk_upload(request):
template = "workforce/csv/schedule_bulk_upload.html"
prompt ={
'Order' : 'Order of the CSV should be avayaid, username, first_name, last_name, emp_id, team, workcode, day_of_week, start_date, start_time, stop_date, stop_time, duration, work_ Memo'
}
if request.method =="GET":
return render(request, template, prompt)
csv_file = request.FILES['file']
if not csv_file.name.endswith('.csv'):
messages.error(request, 'This is not CSV file')
data_set = csv_file.read().decode('utf8')
io_string = io.StringIO(data_set)
next(io_string)
for column in csv.reader(io_string, delimiter=',', quotechar="|"):
_, created = Schedule.objects.custom_update_or_create(
avayaid=column[0],
username=User.objects.get(username=column[1]),
first_name=column[2],
last_name=column[3],
emp_id=column[4],
team=CCTeam.objects.get(team=column[5]),
workcode=WorkCode.objects.get(workcode=column[6]),
# day_of_week=DayofWeek.objects.get(schday=column[7]),
start_date=column[7],
start_time=column[8],
stop_date=column[9],
stop_time=column[10],
created_by=request.user.username,
modified_by=request.user.username
)
context = { 'created':created }
return render(request, template, context)
This is my models.py:
class UnitOfMeasurement(models.Model):
active = models.BooleanField(default=True)
name = models.CharField(max_length=255)
measurement_type = models.CharField(max_length=255)
def __str__(self):
return self.name
class Category(models.Model):
name = models.CharField(max_length=250)
abbreviation=models.CharField(max_length=10)
active = models.BooleanField(default=True)
description=models.CharField(max_length=500,blank=True, null=True)
def __str__(self):
return self.name
class Product(models.Model):
active = models.BooleanField(default=True)
bar_code = models.CharField(max_length=50, blank = True, null = True)
name = models.CharField(max_length=250)
category = models.ForeignKey(
Category, on_delete=models.CASCADE, related_name='product')
brand = models.CharField(max_length=250)
model = models.CharField(max_length=250)
tag = models.CharField(max_length=250, null=True)
remarks = models.TextField(null=True)
gstcode = models.ForeignKey(
GSTCode, on_delete=models.CASCADE, related_name='product', null=True)
unit_of_measurement = models.ForeignKey(
UnitOfMeasurement, on_delete=models.DO_NOTHING, related_name='category')
# picture
objects=ProductManager()
# select the product where active=true & quantity<0
def __str__(self):
return self.name
So how do I need to code my serializers and views in order to get the data that returns name, category, brand, model, tag from Product Model and name from Category Model and also name and measurement_type from UnitOfMeasurement Model?
You can select fields from model in serializer as below example code for UnitOfMeasurement and use this serializer for get(retrieve) request.
class UnitOfMeasurementSerializer(serializers.ModelSerializer):
class Meta:
model = UnitOfMeasurement
fields = ["name", "measurement_type"]
Same thing you can do for rest of models.
Views depends on your use case.
I'm trying to get the id of another class using the filter and I'm not getting it because None appears.
This is the method used:
def total(self):
soma = Venda.objects.filter(id=self.id).aggregate(total=Sum('item__qtde', flat = True))
return soma['total']
result
Below the complete class:
class Venda(models.Model):
id = models.AutoField(u'AÇAIEX', primary_key=True)
hora_saida = models.TimeField(max_length=6)
responsavel_frete = models.CharField(max_length=14, verbose_name=u'Resp. Frete', choices = RESPONSAVEL_FRETE, default='REMETENTE')
empresa = models.ForeignKey(Empresa, on_delete=models.CASCADE)
localidade_origem = models.ForeignKey(Localidade, on_delete=models.CASCADE, verbose_name=u'Loc. Origem', related_name ='localidade_origem')
localidade_destino = models.ForeignKey(Localidade, on_delete=models.CASCADE, verbose_name=u'Loc. Destino', related_name ='localidade_destino')
cliente_origem = models.ForeignKey(Cliente, on_delete=models.CASCADE, related_name ='cliente_origem')
cliente_destino = models.ForeignKey(Cliente, on_delete=models.CASCADE, related_name ='cliente_destino')
carro = models.ForeignKey(Carro, on_delete=models.CASCADE)
motorista_principal = models.ForeignKey(Motorista, on_delete=models.CASCADE, related_name ='motorista_principal')
motorista_reserva = models.ForeignKey(Motorista, on_delete=models.CASCADE , related_name ='motorista_reserva', null=True, blank=True)
#valores default
data_venda = models.DateField(auto_now_add=True, verbose_name=u'Data',)
situacao_venda = models.CharField(max_length=10, verbose_name=u'Situação', choices = SITUACAO_VENDA, default='ATIVA')
#aba de valores teste
tipo_frete = models.CharField(max_length=10, choices = TIPO_FRETE, default='PAGO')
dinheiro = models.BooleanField()
cartao = models.BooleanField()
cartoes = models.CharField(max_length=30, choices = CARTOES, default='DINNER CLUBS', null=True, blank=True)
ano_processo = models.CharField(max_length=4, choices = CARTOES, default='VISA', null=True, blank=True)
#valor_nota = models.DecimalField(verbose_name=u'Valor Nota',
# max_digits=15, decimal_places=2, null=True, blank=True)
valor_dinheiro = models.DecimalField(verbose_name=u'Valor Dinheiro',
max_digits=15, decimal_places=2, default=Decimal('0.00'))
valor_cartao = models.DecimalField(verbose_name=u'Valor Cartão',
max_digits=15, decimal_places=2, default=Decimal('0.00'))
usuario = models.ForeignKey(User, on_delete=models.CASCADE)
agencia = models.ForeignKey(Group, on_delete=models.CASCADE, null=True, blank=True)
#produto = models.ManyToManyField(Produto, blank=False, default=None)
#staticmethod
#def autocomplete_search_fields():
# return id,
#staticmethod
def autocomplete_search_fields():
return 'id',
def __str__(self):
return str(self.id)
def imprimir(self):
return mark_safe("<a target='_blank' href='%s'>Imprimir</a>" % self.get_absolute_url())
imprimir.allow_tags = True
def get_absolute_url(self):
return reverse('venda_detail', args=[self.pk, ])
def get_venda(self):
return Venda.objects.get(pk=self.pk)
#soma o total de volume no relatorio
def total(self):
soma = Venda.objects.filter(id=self.id).aggregate(total=Sum('item__qtde', flat = True))
return soma['total']
def valortotal(self):
soma = Venda.objects.filter(id=self.id).aggregate(valortotal=Sum(F('item__produto__valor') * F('item__qtde'), output_field=FloatField()))
return soma['valortotal']
def valortotalnota(self):
return self.valor_nota
def valor_nota(self, force_insert=False, force_update=False):
valor_nota = self.valor_dinheiro + self.valor_cartao
return valor_nota
def desconto(self):
valortotal = Venda.objects.filter(id=self.id).aggregate(valortotal=Sum(F('item__produto__valor') * F('item__qtde'), output_field=FloatField()))
valor_nota = self.valor_nota
# exemplo de porcetagem return 100 - float(valor_nota.replace(",",".")) * 100 / float(valortotal['valortotal'])
if self.tipo_frete == 'CORTESIA':
return 0.00
else:
return Decimal(valortotal['valortotal']) - valor_nota()
#return valor_nota()
#return float(valortotal['valortotal'])
def clean(self, *args, **kwargs):
valortotal = Venda.objects.filter(id=self.id).aggregate(valortotal=Sum(F('item__produto__valor') * F('item__qtde'), output_field=FloatField()))
valor_nota = self.valor_nota
# if Decimal(valortotal['valortotal']) < valor_nota():
# raise forms.ValidationError("O valor do Tipo de Pagamento (dinheiro + cartão) não pode ser maior que o valor total da nota.")
class Item(models.Model):
produto = models.ForeignKey(Produto, on_delete=models.CASCADE, default=None)
qtde = models.PositiveIntegerField(null=True, blank=False)
venda = models.ForeignKey(Venda, on_delete=models.CASCADE, default=None)
class Manifesto(models.Model):
data_venda = models.DateField(default=timezone.now)
carro = models.ForeignKey(Carro, on_delete=models.CASCADE)
usuario = models.ForeignKey(User, on_delete=models.CASCADE)
def imprimir(self):
return mark_safe("<a target='_blank' href='%s'>Imprimir</a>" % self.get_absolute_url())
imprimir.allow_tags = True
def get_absolute_url(self):
return reverse('manifesto_detail', args=[self.pk, ])
#sem essa função não aparece as variaveis
def get_manifesto(self):
return Manifesto.objects.get(pk=self.pk)
def total(self):
soma = Venda.objects.filter(id=self.id).aggregate(total=Sum('item__qtde', flat = True))
return soma['total']
#Jallisson I don't see you Venda Model, but I think in your Sum() flat=True does not exist. Plus what is qtde?
If you just do Sum('item') instead of Sum('item__qtde') it might work.
one weird thing i see is:
def total(self):
soma = Venda.objects.filter(id=self.id).aggregate(total=Sum('item__qtde', flat = True))
return soma['total']
def total is inside the class Manifesto
But in you def total function you do self.id but self.id is the Id of the Manifesto class so this will never match because it is an id from a different model
I use IntegerField in Answer form for getting id of question page. But IntegerField doesn't get the id page, that get title of this page. I thought it because primary key is title, but not, I tried to set id = models.AutoField(primary_key=True) in Question and Answer models, but the situation is the same. This iss my form class:
class AddAnswerForm(forms.Form):
text = forms.CharField(widget=forms.Textarea)
question = forms.IntegerField()
def clean_question(self):
question_id = self.cleaned_data['question']
try:
question = Question.objects.get(id=question_id)
except Question.DoesNotExist:
question = None
return question
def clean(self):
pass
def save(self):
answer = Answer(**self.cleaned_data)
answer.save()
return answer
That's my models:
class Question(models.Model):
title = models.CharField(default='', max_length=255)
text = models.TextField(default='')
added_at = models.DateTimeField(blank=True, auto_now_add=True)
rating = models.IntegerField(default=0)
author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='question_user')
likes = models.ManyToManyField(User, related_name='question_like_user')
def __str__(self):
return self.title
def get_url(self):
return '/question/{}/'.format(self.id)
class Answer(models.Model):
text = models.TextField(default='')
added_at = models.DateField(blank=True, auto_now_add=True)
question = models.ForeignKey(Question, on_delete=models.SET_NULL, null=True, related_name='answer_question')
author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='answer_user')
def __str__(self):
return self.text
And that's my view:
def question(request, pk):
try:
q = Question.objects.get(id=pk)
except Question.DoesNotExist:
raise Http404
a = Answer.objects.all()
u = User.objects.all()
if request.method == 'POST':
form = AddAnswerForm(request.POST)
if form.is_valid():
_ = form.save()
url = q.get_url()
return HttpResponseRedirect(url)
else:
form = AddAnswerForm(initial={
'question': q,
'answer': a,
'user': u,
})
return render(request, 'question.html',
{
'form': form,
'question': q,
'answer': a,
'user': u,
})
Thank you.
I have the following tables. The ComponentBuild table has two columns 'comp_pn' and 'parent_pn' that are both ForeignKeys. Django is complaining Unknown column 'product_parent_pn.product_id_id. What's the correct way to model these relationship?
class Product(models.Model):
name = models.CharField(max_length=80)
def __unicode__(self):
return self.name
class ProductParentPn(models.Model):
part_no = models.CharField(max_length=80)
product_id = models.ForeignKey(Product)
def __unicode__(self):
return self.part_no
class CompMap(models.Model):
component = models.CharField(max_length=50)
part_no = models.CharField(max_length=50)
def __unicode__(self):
return self.part_no
class CompProductMap(models.Model):
comp_id = models.IntegerField()
prod_id = models.IntegerField()
class Meta:
db_table = u'comp_product_map'
class ComponentBuild(models.Model):
comp_sn = models.CharField(max_length=35)
parent_sn = models.CharField(max_length=15)
comp_pn = models.ForeignKey(CompMap)
parent_pn = models.ForeignKey(ProductParentPn)
date = models.DateField(default=datetime.datetime.today())
def __unicode__(self):
return self.comp_sn