This is the error am getting:
QuerySet.annotate() received non-expression(s): 17
What I want is a subquery that will do something similar to the
select * from inecdb.announced_pu_results
where polling_unit_uniqueid in
(
select uniqueid from polling_unit
where lga_id = (select uniqueid from lga where uniqueid= 17)
);
The subquery
obj3 = Pu_results.objects.filter(polling_unit_uniqueid__in=Subquery(Unit.objects.filter(lga_id=obj1)))
is not displaying any result please can any one help
This is my view
if request.method == 'POST':
selected_item = request.POST.get('item_id') #This is from html select box
obj = Lga.objects.get(lga_id=selected_item)
obj1 = obj.lga_id
obj3 = Pu_results.objects.filter(polling_unit_uniqueid__in=Subquery(Unit.objects.filter(lga_id=obj1)))
for obt in obj3:
print(obt.party_score) #I want looping results here
This is my Model
from django.db import models
from django.urls import reverse
#from django.urls import reverse
class Unit(models.Model):
uniqueid = models.IntegerField(primary_key=True)
polling_unit_id = models.IntegerField(blank=False)
ward_id = models.IntegerField(default=False)
lga_id = models.IntegerField(default=False)
uniquewardid = models.IntegerField(default=True)
polling_unit_number = models.CharField(max_length=50, unique=True)
polling_unit_name = models.CharField(max_length=51)
#pulling_unit_number = models.CharField(max_length=50)
polling_unit_description = models.CharField(max_length=300)
lat = models.CharField(max_length=255)
long = models.CharField(max_length=255)
entered_by_user = models.CharField(max_length=50)
date_entered = models.DateTimeField(blank=False)
user_ip_address = models.CharField(max_length=50)
def get_absolute_url(self):
#return f"/products/{self.id}/"
return reverse("polling:inec-pull-result", kwargs={"uniqueid": self.uniqueid})
class Lga(models.Model):
uniqueid = models.AutoField(primary_key=True)
lga_id = models.IntegerField()
lga_name = models.CharField(max_length=50)
state_id = models.IntegerField()
lga_description = models.TextField(blank=True, null=True)
entered_by_user = models.CharField(max_length=50)
date_entered = models.DateTimeField()
user_ip_address = models.CharField(max_length=50)
class Meta:
db_table = 'lga'
class Article(models.Model):
title = models.CharField(max_length=120)
content = models.TextField()
active = models.BooleanField(default=True)
You need to make sure that the queryset you use for the subquery returns just one column, use values() for that. Note that Subquery isn't needed:
units = Unit.objects.filter(lga_id=obj1).values('uniqueid')
obj3 = Pu_results.objects.filter(polling_unit_uniqueid__in=units)
Read the documentation for the in lookup for a more detailed explanation of passing a QuerySet to in.
This also works:
obj3 = Pu_results.objects.filter(
polling_unit_uniqueid__in = Subquery(
Unit.objects.values('uniqueid').filter(lga_id=obj1)
)
)
Related
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 have a functioning search function shown below, it works without issue. We are redesigning the system, the area_easting value now sits in its own table (model). To get to the area_easting he route is as follows: Trench.trench_id --> Context.context_id --> Sample.sample_id (I know this is non-standard notation).
So how would I traverse these joins? Something like:
qs = qs.filter(sample_id__context_id__trench_id__area_easting__icontains=easting_query)
Which returns Unsupported lookup 'context_id' for AutoField or join on the field not permitted.
from excavation.models import Trench, Context, Sample
from ceramic.models import Ceramic
...
def CeramicFliterView(request):
qs = Sample.objects.all()
easting_query = request.GET.get('area_easting')
if easting_query != '' and easting_query is not None:
qs = qs.filter(area_easting__icontains=easting_query)
...
Models.py
class Trench(models.Model):
trench_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=500, default='', blank=True, null=True)
area_easting = models.IntegerField()
area_northing = models.IntegerField()
...
class Context(models.Model):
context_id = models.AutoField(primary_key=True)
trench_id = models.ForeignKey(Trench, db_column='trench_id', on_delete = models.PROTECT)
...
class Sample(models.Model):
sample_id = models.AutoField(primary_key=True)
context_id = models.ForeignKey(Context, db_column='context_id', on_delete = models.PROTECT)
...
class Ceramic(models.Model):
ceramic_id = models.AutoField(primary_key=True)
sample_id = models.ForeignKey(Sample, db_column='sample_id', on_delete = models.PROTECT)
i have this model
class Post(models.Model):
auth = models.ForeignKey(settings.AUTH_USER_MODEL,default=1)
title = models.CharField(max_length=120)
DESCSPECSOFT = (
(u'Null','Null'),
(u'Phone',u'Phone'),
(u'Car',u'Car'),
(u'Laptop',u'Laptop'),
(u'jops',u'Jops'),
(u'Electronic',u'Electronic'),
(u'Clothes',u'Clothes'),
(u'Makeup',u'Makeup'),
(u'Furnishings',u'Furnishings'),
(u'books',u'books'),
(u'sports',u'sports'),
(u'Property',u'Property'),
(u'Other',u'Other'),
)
City = (
(u'Null','Null'),
(u'Kosti',u'Kosti'),
(u'Khartoum',u'Khartoum'),
(u'Rabbik',u'Rabbik'),
(u'Duwaim',u'Duwaim'),
(u'Sinnar',u'Sinnar'),
(u'Bahri',u'Bahri'),
(u'Omdurman',u'Omdurman'),
(u'Sawakin',u'Sawakin'),
(u'Port Sudan',u'Port Sudan'),
(u'Kasala',u'Kasala'),
(u'Madani',u'Madani'),
(u'Alabid',u'Alabid'),
)
Case = (
(u'Null','Null'),
(u'New',u'New'),
(u'Old',u'Old'),
(u'Second Hand',u'Second Hand'),
(u'Other',u'Other'),
)
Type = models.CharField(choices=DESCSPECSOFT, default='Null',blank = False,null = False,max_length=120)
company = models.CharField(max_length=120)
dis = models.TextField(default="in here you w,ll write all the discribtion about your product")
image = models.ImageField(null=True,blank=True,width_field="width_field", height_field="height_field")
width_field = models.IntegerField(default=0)
height_field = models.IntegerField(default=0)
case = models.CharField(choices=Case, default=99,blank = False,null = False,max_length=120)
price = models.BigIntegerField(default=0)
city = models.CharField(choices=City, default='Null',blank = False,null = False,max_length=120)
address = models.CharField(max_length=120)
draft = models.BooleanField(default=False)
#pup = models.DateField(auto_now=False,auto_now_add=False ,null=False)
date = models.DateTimeField(auto_now=True ,auto_now_add=False)
puplis = models.DateTimeField(auto_now=False ,auto_now_add=True)
objects = PostManager()
def __str__(self):
return self.title
def __unicode__(self):
return self.title
any user can add a post but i want the user name show in the data base means the user how add the post because every post show the admin name not the user how add the post can someone show me haw can i fix this ???
sorry my en is bad ...
I have this 2 models:
class BuildingStructure(models.Model):
bldg_name = models.CharField(max_length=100)
height = models.FloatField()
code = models.CharField(max_length=25)
block_name = models.CharField(max_length=75)
bldg_type = models.CharField(max_length=50)
brgy_locat = models.CharField(max_length=50)
geom = models.MultiPointField(srid=32651, null=True, blank=True)
objects = models.GeoManager()
def __unicode__(self):
return self.bldg_name
class FloodHazard(models.Model):
gridcode = models.IntegerField()
hazard = models.CharField(max_length=6)
date_field = models.CharField(max_length=50)
geom = models.MultiPolygonField(srid=32651, null=True, blank=True)
objects = models.GeoManager()
def __unicode__(self):
return self.hazard
hazard field in the model has the following values: 'High', 'Medium', 'Low'.
I wanted to create a report in a table format(HTML) like this:
I tried this so far:
getgeom = FloodHazard.objects.get(id=512).geom
getgeom_medium = FloodHazard.objects.get(id=620).geom
getgeom_low = FloodHazard.objects.get(id=638).geom
response_data = {}
response_data["medium"] = list(BuildingStructure.objects.filter(geom__intersects=getgeom_medium).values( 'brgy_locat').annotate(countmedium=Count('brgy_locat')))
response_data["high"] = list(BuildingStructure.objects.filter(geom__intersects=getgeom).values('brgy_locat').annotate( counthigh=Count('brgy_locat')))
response_data["low"] = list(BuildingStructure.objects.filter(geom__intersects=getgeom_low).values('brgy_locat').annotate( countlow=Count('brgy_locat')))
result = {}
for category in response_data.values():
for element in category:
key = element.pop('brgy_locat')
if key not in result:
result[key] = {"loc":key}
result[key].update(element)
json_result = result.values()
return HttpResponse(list(json.dumps(json_result)), content_type='application/json')
The above code works fine as I am able to get my intended output. But as you examine it, I tried one id in each hazard type. So my problem now is to use filter to get all the ids and used it as reference in my GeoQuerySet. Any help will be appreciated. I'm trying to pass the data as JSON in my template because I'm using datatables.
This is how I get all the ids for e.g. hazard type "high"
reference = FloodHazard.objects.filter(hazard='High')
ids = reference.values_list('id', flat=True)
for id in ids:
#something has to be done here...
Hello i have the following problem (sorry for my bad english)
I have the following models
I have 3 models which "Prediccion" has two foreign keys from "Juego" model and "Usuario"model
class Juego(models.Model):
#id = models.IntegerField(primary_key=True, db_column='Id')
equipoa = models.CharField(max_length=135, db_column='EquipoA')
equipob = models.CharField(max_length=135, db_column='EquipoB')
resultadoa = models.IntegerField(null=True, db_column='ResultadoA', blank=True)
resultadob = models.IntegerField(null=True, db_column='ResultadoB', blank=True)
fecha = models.DateField(null=True, db_column='Fecha', blank=True)
class Meta:
db_table = u'juego'
class Usuario(models.Model):
# id = models.IntegerField(primary_key=True, db_column='Id') # Field name made lowercase.
nombre = models.CharField(max_length=135, db_column='Nombre')
fechanacimiento = models.DateField(null=True, db_column='FechaNacimiento', blank=True)
nombreusuario = models.CharField(max_length=135, db_column='NombreUsuario')
clave = models.CharField(max_length=135, db_column='Clave')
class Meta:
db_table = u'usuario'
class Prediccion(models.Model):
#id = models.IntegerField(primary_key=True, db_column='Id')
idusuario = models.ForeignKey(AuthUser, db_column='IdUsuario')
idjuego = models.ForeignKey(Juego, db_column='IdJuego') # Field name made lowercase.
equipoa = models.IntegerField(null=True, db_column='EquipoA', blank=True)
equipob = models.IntegerField(null=True, db_column='EquipoB', blank=True)
resultado = models.IntegerField(null=True, db_column='Resultado', blank=True)
class Meta:
db_table = u'prediccion'
And have I have the following view
from django.shortcuts import render_to_response
from scorecenter.JuegoApp.models import Juego
from scorecenter.PrediccionApp.models import Prediccion
from scorecenter.PrediccionApp.models import TipoResultado
from scorecenter.PrediccionApp.models import AuthUser
def juegosap(request, pagina="1", idgame=-1, resa=-1, resb=-1):
if(idgame==-1 and resa==-1 and resb==-1):
pag = int(pagina)
pag = pag-1
lista = Juego.objects.order_by('-fecha', '-id')[pag*4:pag*4+4]
template_name = 'juegos_semana.html'
return render_to_response(template_name,{'lista':lista})
else:
game = Juego.objects.get(id=int(idgame))
print(game.equipoa)
print(game.id)
user = AuthUser.objects.get(username=request.user)
print(user.username)
temporal = Prediccion(idusuario = user, idjuego = game, equipoa=int(resa), equipob=int(resb))
temporal.resultado = 1
temporal.save()
pag = int(pagina)
pag = pag-1
lista = Juego.objects.order_by('-fecha')[pag*4:pag*4+4]
template_name = 'juegos_semana.html'
return render_to_response(template_name,{'lista':lista})
But I am getting the following error:
Cannot assign "<Juego: Juego object>": "Prediccion.idjuego" must be a "Juego" instance.
in the next line:
temporal = Prediccion(idusuario = user, idjuego = game, equipoa=int(resa), equipob=int(resb))
your idjuego is a foreign key so the value must equivalent to id,
try:
temporal = Prediccion(idusuario = user, idjuego = game.id, equipoa=int(resa), equipob=int(resb))
Also, in each of your model, please put unicode so that it will not return "< object >". Here is a sample:
def __unicode__(self):
return self.field_name
temporal.idjuego_id = game.id
temporal.save()
ForeignKey fields store their value in an attribute with _id at the end, which you can access directly to avoid visiting the database.
The _id version of a ForeignKey is a particularly useful aspect of Django, one that everyone should know and use from time to time when appropriate.