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
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)
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.
These are my django models.
explaination of db models :
thinkpad is a equipment of laptop subcategory.and laptop subcategory has a category called electronics.
now laptop can have many attributes like processor,ram,color,screen_size.
Question :
Find out all the equipment with theirequipment detail ,subcategory_name and attribute names,value which have category_id =1 .
Models :
class Category(models.Model):
category_id = models.AutoField(primary_key=True, default=None)
category_name = models.CharField(max_length=15, unique=True)
created_at = models.DateTimeField(auto_now_add=True)
last_modified = models.DateTimeField(auto_now=True)
def __str__(self):
return str(self.category_id)+","+self.category_name
class Meta:
db_table = "category"
class Subcategory(models.Model):
subcategory_id = models.AutoField(primary_key=True, default=None)
category = models.ForeignKey(
Category, on_delete=models.CASCADE, related_name="category_subc", verbose_name="category_id")
subcategory_name = models.CharField(max_length=15, unique=True)
created_at = models.DateTimeField(auto_now_add=True)
last_modified = models.DateTimeField(auto_now=True)
def __str__(self):
return str(self.subcategory_id)+","+self.subcategory_name
class Meta:
db_table = "subcategory"
class Equipment(models.Model):
equipment_id = models.AutoField(primary_key=True, default=None)
subcategory = models.ForeignKey(
Subcategory, on_delete=models.CASCADE, related_name="subcategory_eq", verbose_name="subcategory_id")
created_at = models.DateTimeField(auto_now_add=True)
last_modified = models.DateTimeField(auto_now=True)
def __str__(self):
return str(self.equipment_id)
class Meta:
db_table = "equipment"
class Attribute(models.Model):
attribute_id = models.AutoField(primary_key=True, default=None)
attribute_name = models.CharField(max_length=15, unique=True)
subcategory = models.ManyToManyField(
Subcategory, through="SubcategoryAttributeMap")
created_at = models.DateTimeField(auto_now_add=True)
last_modified = models.DateTimeField(auto_now=True)
def __str__(self):
return str(self.attribute_id)+","+self.attribute_name
class Meta:
db_table = "attribute"
class SubcategoryAttributeMap(models.Model):
id = models.AutoField(primary_key=True, default=None)
subcategory = models.ForeignKey(
Subcategory, on_delete=models.CASCADE, related_name="subcategory_sub_attr_map", verbose_name="subcategory_id")
attribute = models.ForeignKey(
Attribute, on_delete=models.CASCADE, related_name="attribute_sub_attr_map", verbose_name="attribute_id")
created_at = models.DateTimeField(auto_now_add=True)
last_modified = models.DateTimeField(auto_now=True)
def __str__(self):
return str(self.id)
class Meta:
db_table = "subcategory_attribute_map"
class EquipmentDetail(models.Model):
equipment_detail_id = models.AutoField(primary_key=True, default=None)
equipment = models.ForeignKey(
Equipment, on_delete=models.CASCADE, related_name="equipment_eqdetail", verbose_name="equipment_id")
attribute = models.ForeignKey(
Attribute, on_delete=models.CASCADE, related_name="attribute_eqdetail", verbose_name="attribute_id")
value = models.CharField(max_length=15)
created_at = models.DateTimeField(auto_now_add=True)
last_modified = models.DateTimeField(auto_now=True)
def __str__(self):
return str(self.equipment_detail_id)+","+self.value
class Meta:
db_table = "equipment_detail"
Desired Output:
[
{
'equipment_id':1,
'subcategory__name':'laptop',
'attribute_detail':[
{
'attribute_name':'color',
'attribute_value':'red'
},
{
'attribute_name':'ram',
'attribute_value':'6gb'
}
]
},
{ 'equipment_id':2,
'subcategory__name':'Mouse',
'attribute_detail':[
{
'attribute_name':'color',
'attribute_value':'red'
},
{
'attribute_name':'dpi',
'attribute_value':'800'
}
]
}
]
Try this:
equipments= Equipment.objects.select_related('subcategory').filter(subcategory__category_id=1).prefetch_related(Prefetch('equipment_eqdetail', EquipmentDetail.objects.select_related('attribute')))
results = []
for equipment in equipments:
temp = {
'equipment_id': equipment.id,
'subcategory__name': equipment.subcategory.name,
}
attributes = []
for eq_detail in equipment.equipment_eqdetail.all():
attributes.append({'attribute_name': eq_detail.attribute.attribute_name, 'attribute_value': eq_detail.value})
temp['attribute_detail'] = attributes
results.append(temp)
There will be 2 sql queries for this lookup and this will return data in your desired format.
I got the answer for this .
equipments = Equipment.objects.filter(subcategory__category__category_id=1)
all_equipments_data = []
# iterate over each equipment
for equipment in equipments:
single_equipment_data = {}
single_equipment_data['equipment_id'] = equipment.equipment_id
single_equipment_data['subcategory__name'] = equipment.subcategory.subcategory_name
attributes_detail_of_equipment = []
# iterate over each equipmentdetail of single equipment
for eqdetail in equipment.equipment_eqdetail.all():
attributes_detail_of_equipment.append({'attribute_name':eqdetail.attribute.attribute_name,'attribute_value':eqdetail.value})
single_equipment_data['attribute_detail'] = attributes_detail_of_equipment
all_equipments_data.append(single_equipment_data)
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