hi i have a problem with this filter. group_to_add takes some values which should filter out the problem that I don't want those values but I want the others without those.
I would like to find a way to take those values and subtract them from others.
group_to_add = DatiGruppi.objects.filter(gruppi_scheda = scheda.id)
GruppiForm.base_fields['dati_gruppo'] = forms.ModelChoiceField(queryset = group_to_add)
I asked a similar question I leave the link
select filtering and removal if they are already present in the db
models
class Schede(models.Model):
nome_scheda = models.CharField(max_length=100)
utente = models.ForeignKey(User, on_delete = models.CASCADE,related_name = 'utente')
class DatiGruppi(models.Model):
dati_gruppo = models.ForeignKey(Gruppi,on_delete = models.CASCADE, related_name = 'dati_gruppo')
gruppi_scheda = models.ForeignKey(Schede,on_delete = models.CASCADE, related_name = 'gruppi_scheda')
class Gruppi(models.Model):
nome_gruppo = models.CharField(max_length=100)
I have this tab where inside there are saved data groups that contain groups that are inside a select the correct exclusion would be
group_to_add = Gruppi.objects.exclude(dati_gruppo = 147)
but instead of 147 I have to put the id of the data group of that board
view
def creazione(request, nome):
scheda = get_object_or_404(Schede, nome_scheda = nome)
eserciziFormSet = formset_factory(EserciziForm, extra = 0)
if request.method == "POST":
gruppo_form = GruppiForm(request.POST, prefix = 'gruppo')
if gruppo_form.is_valid():
gruppo = gruppo_form.save(commit = False)
gruppo.gruppi_scheda = scheda
gruppoName = gruppo_form.cleaned_data['dati_gruppo']
gruppo.save()
esercizi_formset = eserciziFormSet(request.POST, prefix='esercizi')
for esercizi in esercizi_formset:
esercizi_instance = esercizi.save(commit = False)
esercizi_instance.gruppo_single = get_object_or_404(DatiGruppi, gruppi_scheda = scheda.id, dati_gruppo = gruppoName)
esercizi_instance.save()
return HttpResponseRedirect(request.path_info)
else:
group_to_add = Gruppi.objects.exclude(dati_gruppo = 147)
GruppiForm.base_fields['dati_gruppo'] = forms.ModelChoiceField(queryset = group_to_add)
gruppo_form = GruppiForm(prefix = 'gruppo')
esercizi_formset = eserciziFormSet(prefix='esercizi')
context = {'scheda' : scheda, 'gruppo_form' : gruppo_form, 'esercizi_formset': esercizi_formset}
return render(request, 'crea/passo2.html', context)
If I understand it correctly, you should use .exclude(…) [Django-doc] not .filter(…) [Django-doc]:
group_to_add = Gruppi.objects.exclude(
dati_gruppo__gruppi_scheda=scheda
)
GruppiForm.base_fields['dati_gruppo'] = forms.ModelChoiceField(queryset=group_to_add)
I am creating an api which returns weather data of particular city for n number of days given.(api definition: weatherdata/city_name/ndays/).I have problem sorting out data for ndays.
I sorted out the city name using simple icontains. similarly I want to sort out for ndays. previous ndays data needs to be shown. example: suppose today is 2019-08-29, on providing ndays to be 6, weather data of particular city has to be provided from 2019-08-24 to 2019-08-26.
views.py
class weatherDetail(APIView):
def get_object(self, city_name, ndays):
try:
x = weatherdata.objects.filter(city_name__icontains=city_name)
now = datetime.datetime.now()
fromdate = now - timedelta(days=ndays)
y =
return x
except Snippet.DoesNotExist:
raise Http404
def get(self,*args,**kwargs):
city_name = kwargs['city_name']
snippet = self.get_object(city_name,ndays)
serializer = weatherdataserializer(snippet,many =True)
return Response(serializer.data)
models.py
class weatherdata(models.Model):
city_name = models.CharField(max_length = 80)
city_id = models.IntegerField(default=0)
latitude = models.FloatField(null=True , blank=True)
longitude = models.FloatField(null=True , blank=True)
dt_txt = models.DateTimeField()
temp = models.FloatField(null = False)
temp_min = models.FloatField(null = False)
temp_max = models.FloatField(null = False)
pressure = models.FloatField(null = False)
sea_level = models.FloatField(null = False)
grnd_level = models.FloatField(null = False)
humidity = models.FloatField(null = False)
main = models.CharField(max_length=200)
description = models.CharField(max_length=30)
clouds = models.IntegerField(null=False)
wind_speed = models.FloatField(null = False)
wind_degree = models.FloatField(null = False)
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('weatherdata/', views.weatherList.as_view()),
path('weatherdata/<str:city_name>/<int:ndays>/', views.weatherDetail.as_view()),
]
I want 'y' to be filtering objects based on dates. previous ndays data has to be returned. get_object should return the objects which falls under both x and y what needs to be modified in my code.
You have to change your query like below
class weatherDetail(APIView):
def get_queryset(self, city_name, ndays):
x = weatherdata.objects.filter(city_name__icontains=city_name)
today_date = timezone.now().date()
fromdate = today_date - timedelta(days=ndays)
x = x.filter(dt_txt__gte=fromdate).order_by('dt_txt')
return x
def get(self,*args,**kwargs):
city_name = kwargs['city_name']
snippet = self.get_queryset(city_name, ndays)
serializer = weatherdataserializer(snippet, many=True)
return Response(serializer.data)
class Hardware(models.Model):
date = models.PositiveSmallIntegerField()
node = models.ForeignKey('Node', on_delete=models.CASCADE,null = True)
slot = models.PositiveSmallIntegerField(null = True)
server = models.CharField(max_length=20,null = True)
server_state = models.CharField(max_length=20,null = True)
adapter = models.CharField(max_length=20,null = True)
adapter_state = models.CharField(max_length=20,null = True)
class Meta:
unique_together = ('date', 'node','slot')
order_with_respect_to = 'node'
def __str__(self):
return self.node.name +" " + self.server
class Node(models.Model):
name = models.CharField(max_length = 40, primary_key = True)
def __str__(self):
return self.name
def inventory_by_node(request):
day = (arrow.now().day) - 1
nodes = Node.objects.prefetch_related("hardware_set").all()
return render(request, 'automation/inventory_by_node.html',{'nodes':nodes})
I need to filter hardware_set based on date which is equal to currrent day. I tried
nodes = Node.objects.prefetch_related(Prefetch("hardwares", quesryset=Hardware.objects.filter(date=day)).all()
but It didn't works says no Pretch is defined
Try this:
prefetch = Prefetch("hardware_set", queryset=Hardware.objects.filter(date=day))
nodes = Node.objects.prefetch_related(prefetch).all()
I'm working on a inventory control in Django and i want a form to control the action that will be made. If a record for the product already exist, it should update the quantity. If it doesn't exist, it should create the record for it. Besides that, one form field will have three choices. One will add the form value to que product quantity, other will subtract and another one will change to the value in the form.
The model is quite big, because i set some choices for the form fields. There it is:
from django.db import models
from django import forms
from django.forms import ModelForm
class Produto(models.Model):
CAMISA = "CM"
QUADRO = "QD"
CANECA = 'CN'
ESCOLHAS_PRODUTO = (
(CAMISA, 'Camisa'),
(QUADRO, 'Quadro'),
(CANECA, 'Caneca'),
)
tipo = models.CharField(max_length = 40,
choices=ESCOLHAS_PRODUTO,
default=CAMISA)
class Camisa(Produto):
MASCULINA = 'MA'
FEMININA_BASICA = 'FB'
FEMININA_GOLA_V = 'FV'
INFANTIL = 'IN'
MODELO_CAMISA = (
(MASCULINA, 'Masculina'),
(FEMININA_BASICA, 'Feminina Basica'),
(FEMININA_GOLA_V, 'Feminina Gola V'),
(INFANTIL, 'Infantil'),
)
modelo = models.CharField(max_length = 50,
choices=MODELO_CAMISA,
)
AMARELA = 'AM'
AZUL_CLARO = 'AC'
AZUL_ESCURO = 'AE'
BRANCA = 'BR'
CINZA = 'CI'
LARANJA = 'LA'
MARFIM = 'MA'
ROSA = 'RO'
PRETA = 'PR'
VERDE_MUSGO = 'VM'
VERMELHA = 'VR'
CORES_CAMISA = (
(AMARELA, 'Amarela'),
(AZUL_CLARO, 'Azul Claro'),
(AZUL_ESCURO, 'Azul Escuro'),
(BRANCA, 'Branca'),
(CINZA, 'Cinza'),
(LARANJA, 'Laranja'),
(MARFIM, 'Marfim'),
(ROSA, 'Rosa'),
(PRETA, 'Preta'),
(VERDE_MUSGO, 'Verde Musgo'),
(VERMELHA, 'Vermelha'),
)
cor = models.CharField(max_length = 40,
choices=CORES_CAMISA,
)
TAMANHO_P = 'TP'
TAMANHO_M = 'TM'
TAMANHO_G = 'TG'
TAMANHO_GG = 'GG'
TAMANHO_XG = 'XG'
TAMANHO_02_ANOS = '02'
TAMANHO_04_ANOS = '04'
TAMANHO_06_ANOS = '06'
TAMANHO_08_ANOS = '08'
TAMANHO_10_ANOS = '10'
TAMANHO_12_ANOS = '12'
TAMANHO_14_ANOS = '14'
TAMANHO_CAMISA = (
(TAMANHO_P, 'P'),
(TAMANHO_M, 'M'),
(TAMANHO_G, 'G'),
(TAMANHO_GG, 'GG'),
(TAMANHO_XG, 'XGG'),
(TAMANHO_02_ANOS, '2 Anos'),
(TAMANHO_04_ANOS, '4 Anos'),
(TAMANHO_06_ANOS, '6 Anos'),
(TAMANHO_08_ANOS, '8 Anos'),
(TAMANHO_10_ANOS, '10 Anos'),
(TAMANHO_12_ANOS, '12 Anos'),
(TAMANHO_14_ANOS, '14 Anos'),
)
tamanho= models.CharField(max_length = 50,
choices=TAMANHO_CAMISA,
)
quantidade = models.IntegerField()
def __unicode__(self):
return self.modelo
class CamisaForm(ModelForm):
ADICIONAR = 'ADC'
REDUZIR = 'RED'
ALTERAR = 'ALT'
ACOES = (
(ADICIONAR, 'Adicionar Quantidade'),
(REDUZIR, 'Reduzir Quantidade'),
(ALTERAR, 'Alterar para Quantidade'),
)
acoes = forms.ChoiceField(
choices=ACOES,
)
class Meta:
model = Camisa
And the following view:
def index(request):
produtos_estoque = Camisa.objects.all()
template = 'estoque/index.html'
modelos_camisa = {'MA' : 'Masculina Basica','FB' : 'Feminina Basica','FV' : 'Feminina Gola V','IN' : 'Infantil' }
if request.method == 'POST':
form = CamisaForm(request.POST)
if form.is_valid():
try:
produto_atualizar = Camisa.objects.get(modelo = request.POST['modelo'], cor = request.POST['cor'], tamanho = request.POST['tamanho'])
if request.POST['acoes'] == 'ADC':
produto_atualizar.quantidade = produto_atualizar.quantidade + request.POST['quantidade']
elif request.POST['acoes'] == 'RED':
produto_atualizar.quantidade = produto_atualizar.quantidade - request.POST['quantidade']
elif request.POST['acoes'] == 'ALT':
produto_atualizar.quantidade = request.POST['quantidade']
produto_atualizar.save()
except:
produto_atualizar = form.save()
return HttpResponseRedirect('')
else:
form = CamisaForm()
return render_to_response(template, { 'form': form, 'produtos_estoque': produtos_estoque,
'modelos_camisa' : modelos_camisa.iteritems(), }, context_instance=RequestContext(request))
But what is happening is that the form is just creating another record for the product, even if it already exists. Not sure if the rest of the model is important for this question, will post it if necessary. Can somebody help me on this one? Thanks
Please post the Model this is acting on - it will have some useful information, like constraints or lack thereof etc. OK cool, no unique constraints in there causing insert violations.
First thing I would recommend is using the forms cleaned_data to access form values instead of the raw POST data, form.is_valid() does a lot of work to process the raw data into acceptable inputs for Model data.
Second thing is that except clause will catch ANY exception which I suspect is your problem... Something else is going wrong which is creating the new record in the except clause. Be specific, like except Camisa.DoesNotExist:
Third thing is to put those constants on the Model so you can reference them from the Form and View instead of literal strings. This is just a cleanliness / code style recommendation.
A little cleanup might look like:
MODELOS_CAMISA = {'MA' : 'Masculina Basica','FB' : 'Feminina Basica','FV' : 'Feminina Gola V','IN' : 'Infantil' }
def index(request):
produtos_estoque = Camisa.objects.all()
if request.method == 'POST':
form = CamisaForm(request.POST)
if form.is_valid():
try:
produto_atualizar = Camisa.objects.get(modelo=form.cleaned_data.get('modelo'), cor=form.cleaned_data.get('cor'), tamanho=form.cleaned_data.get('tamanho'))
quantidade = form.cleaned_data.get('quantidade')
acoes = form.cleaned_data.get('acoes')
if acoes == Camisa.ADC:
produto_atualizar.quantidade = produto_atualizar.quantidade + quantidade
elif acoes == Camisa.RED:
produto_atualizar.quantidade = produto_atualizar.quantidade - quantidade
elif acoes == Camisa.ALT:
produto_atualizar.quantidade = quantidade
produto_atualizar.save()
except Camisa.DoesNotExist:
produto_atualizar = form.save()
return HttpResponseRedirect('')
else:
form = CamisaForm()
return render_to_response('estoque/index.html', { 'form': form, 'produtos_estoque': produtos_estoque,
'modelos_camisa' : MODELOS_CAMISA.iteritems(), }, context_instance=RequestContext(request))
(Sorry for any grammatical errors, my Portuguese is not great)
That should be enough to get you started, if you add more information I can edit and elaborate my answer. Good luck!
I have a model like this:
class Info(models.Model):
tape_id = models.TextField()
name = models.TextField()
video_type = models.TextField()
date = models.DateTimeField()
director = models.CharField(max_length=255)
cameraman = models.CharField(max_length=255)
editor = models.CharField(max_length=255)
time_code = models.TextField()
tag1 = models.TextField()
User can search from tape_id, name, director and cameraman using the same search input box.
I have a search view like this:
if request.method == 'POST':
search_inp = request.POST['search_box']
tape_id = Info.objects.filter(tape_id__exact=search_inp)
res = Info.objects.filter(name__icontains=search_inp)
res = Info.objects.filter(director__icontains=search_inp)
res = Info.objects.filter(cameraman__icontains=search_inp)
total_video = res.count()
if len(res) == 0 and len(tape_id) == 0 :
result = "No videos found!!"
return render_to_response('no_results_only.html', {'result':result}, context_instance=RequestContext(request))
else:
date1 = [i.date for i in res]
date = [i.strftime("%B %d, %Y") for i in date1]
a = zip(res, date)
return render_to_response('list_videos.html', {'a':a, 'total_video':total_video}, context_instance=RequestContext(request))
return HttpResponseRedirect('/')
I thought it would work at first but it doesn't. First res variable can contain the value whereas the last res be empty which will return to the no_results.html. I want to deploy this search using the same input box. How can I make this work?
First you need to import Q to use for OR filtering:
from django.db.models import Q
Then your code should look like this:
if request.method == 'POST':
search_inp = request.POST['search_box']
res = Info.objects.filter(
Q(tape_id__exact=search_inp) |
Q(name__icontains=search_inp) |
Q(director__icontains=search_inp) |
Q(cameraman__icontains=search_inp)
)
total_video = res.count()
if len(res) == 0:
result = "No videos found!!"
return render_to_response('no_results_only.html', {'result':result}, context_instance=RequestContext(request))
else:
date1 = [i.date for i in res]
date = [i.strftime("%B %d, %Y") for i in date1]
a = zip(res, date)
return render_to_response('list_videos.html', {'a':a, 'total_video':total_video}, context_instance=RequestContext(request))
return HttpResponseRedirect('/')
It is recommended to apply OR conditions in the filter. You can refer the documentation for the syntax.
Q(question__startswith='Who') | Q(question__startswith='What')
It will make sure that you will get an unique list of objects in the result.