Query Values Muliple Field Foreign Key Column - django

This is my model:
class Personel(models.Model):
Numara = models.IntegerField(max_length=10)
Isim = models.CharField(max_length=30)
Soyisim = models.CharField(max_length=30)
class Islem(models.Model):
MenuAd = models.CharField(max_length=30)
Tarih = models.DateTimeField(auto_now_add=True)
Personel = models.ForeignKey(Personel)
Durum = models.PositiveIntegerField(max_length=5)
This is my query:
sorgu = Islem.objects.all().values('MenuAd', 'Personel')
sorgu result:
[{'MenuAd': 'Deneme', 'Personel': 2 }]
but, i want to result:
[{'MenuAd': 'Deneme', 'Personel': '2 - Baris Halici'}]
Numara: 2
Isim: Baris
Soyisim: Halici
example - proposal
def get_full_personel(self):
return "'%s - %s %s" % (self.Numara, self.Isim, self.Soyisim)
Thanks,

try changing your:
class Personel(models.Model):
def __unicode___(self):
return "'%s - %s %s" % (self.Numara, self.Isim, self.Soyisim)
or ___str___(self): if using python 3.
although that may not solve it... try:
sorgu = Islem.objects.all().values('MenuAd', 'Personel__get_full_personel')

Related

Django: Aggregate and Sum with a join with another table without the forign key constraint

Here is my models.py file.
from django.db import models
from django.contrib.auth.models import User
class image(models.Model):
name = models.CharField(max_length = 200)
src = models.URLField()
alt = models.CharField(max_length = 200)
points = models.IntegerField(default = 0)
id = models.CharField(max_length = 200, primary_key = True)
hotelId = models.IntegerField()
def __unicode__(self):
return self.name
class imagescore(models.Model):
user = models.ForeignKey(User)
image_id = models.CharField(max_length = 200)
score = models.IntegerField(default = 1)
createdTime = models.DateTimeField(auto_now_add =True)
def __unicode__(self):
if self.score < 0:
status = " rejected "
else:
status = "approved"
return (self.user+ status+ image_id)
pass
I would like to pass on to my template a table that is a result of the SQL Query:
select ei.id,ei.src, ei.hotelId , sum(score)
from eyeballing_image ei LEFT join eyeballing_imagescore eis on ei.id = eis.image_id
where user_id = request.user.id and ei.hotelId = 56565
group by
ei.id,ei.src, ei.hotelId
My app name is eyeballing. O tried using joins and filters bot i couldn't make it work.
Additionally, i tried making the sum(score) part into a separate dict and check the same in the template. Didn't work
Any help will be appreciated.
Your query has two problems, one in column name hotelId. you must use it in query in this way ei."hotelId".
Other problem is in condition user_id = request.user.id because you have not request in sql and you must replace it with a value.
Maybe another problem is in return (self.user + status + image_id) that must be return (self.user + self.status + self.image_id).

How Serializing many-to-many through Foreign Key Django?

I have model "B" with many-to-many through Foreign Key:
class DManager(m.Manager):
def get_by_natural_key(self, name):
return self.get(name=name)
class D(m.Model):
objects = DManager()
id = m.AutoField(primary_key=True)
name = m.CharField(max_length=250, unique=True, null=False)
def natural_key(self):
return (self.name)
class A(m.Model):
id = m.IntegerField(unique=True, null=False, primary_key=True)
name = m.CharField(max_length=250, null=True)
class B(m.Model):
id = m.IntegerField(unique=True, null=False, primary_key=True)
name = m.CharField(max_length=250, null=True)
type = m.ForeignKey(D)
bs = m.ManyToManyField(A, through='C')
def natural_key(self):
## ?natural key for many-to-many?
return(self.name, self.type.natural_key(), ?????)
class C(m.Model):
a_id = m.ForeignKey(A)
b_id = m.ForeignKey(B)
I can get relation through foreign key (B-D), but I can't get relation from many-to-many (B-A) in my ajax.py:
....
if request.is_ajax():
aj_d = json.loads(request.body.decode('utf-8'))
raw_data = serializers.serialize(
'python', m.B.objects.filter(
bs__a_id__in=aj_d['data']).distinct(),
use_natural_foreign_keys=True)
output = json.dumps(raw_data)
return HttpResponse(output, content_type='application/json')
Maybe exist another way through values() for example. But I have problem with dumps list of dicts - "is not JSON serializable":
...
raw_data = m.B.objects.filter(
bs__a_id__in=aj_d['data']).distinct().values()
output = json.dumps(raw_data)
Solution:
def push_data(request):
q = m.B.objects
if request.is_ajax():
data = json.loads(request.body.decode('utf-8'))
if 'req_1' in data:
q = q.filter(bs__id__in=data['req_1'])
if 'req_2' in data:
q = q.filter(type__id__in=data['req_2'])
actual_data = q.values('name', 'id', 'type__name')
mtm_get(actual_data) ## down
return HttpResponse(json.dumps(list(actual_data)),
content_type='application/json; charset=utf8')
for many-to-many:
def mtm_get(data):
for d in data:
d['a_name'] = ', '.join(''.join(i) for i in m.B.objects.filter(
pk=d['id']).values_list('bs__name'))

IntegrityError : yonetim_ders.ogretim_elemani_id may not be NUL

My models.py:
from django.db import models
class OgretimElemani(models.Model):
adi = models.CharField(max_length=50)
soyadi = models.CharField(max_length=50)
telefonu = models.CharField(max_length = 10 , blank=True)
e_posta_adresi = models.EmailField(blank=True)
def __unicode__(self):
return '%s %s' % (self.soyadi,self.adi)
class Ders(models.Model):
kodu = models.CharField(max_length=10)
adi = models.CharField(max_length=50)
ogretim_elamani = models.ForeignKey(OgretimElemani)
tanimi = models.CharField(max_length=1000,blank = True)
def __unicode__(self):
return '%s %s %s' % (self.kodu,self.adi,self.ogretim_elamani)
class Ogrenci(models.Model):
numarasi = models.IntegerField()
adi = models.CharField(max_length=50)
soyadi = models.CharField(max_length=50)
aldigi_dersler = models.ManyToManyField(Ders)
def __unicode__(self):
return '%s %s %s' % (self.soyadi,self.adi,self.aldigi_dersler)
Django shell :
>>>ders1=Ders(kodu='KIM101', adi='Kimya-1')
>>>ders1.ogretim_elemani=OgretimElemani[0]
>>>ders1.save()
IntegrityError : yonetim_ders.ogretim_elemani_id may not be NULL
You must assign a OgretimElemani instance that has already been saved to the database.
For example, the following should work.
>>> ders1 = Ders(kodu='KIM101', adi='Kimya-1'
>>> ogretim_elemani = OgretimElemani.objects.all()[0] # fetch the first one from the database
>>> ders1.ogretim_elemani = ogretim_elemani
>>>ders1.save()
Your example is not very clear because you use OgretimElemani[0]. You shouldn't reuse the variable name OgretimElemani, it makes the code confusing.

django sort on calculated model field -- can I use .extra?

I have the model below. I want to order by percent_vote. I know I could calculate the value and save to a new field in the model, but I prefer not to go that way. Is there some way to use .extra method to do this?
Django 1.6, sqlite3
class HallOfFame(models.Model):
player = models.ForeignKey(Master)
year = models.IntegerField(db_index=True)
voted_by = models.CharField(max_length=30)
ballots_cast = models.IntegerField()
votes_needed = models.IntegerField()
votes_received = models.IntegerField(db_index=True)
inducted = models.BooleanField(db_index=True)
category = models.CharField(max_length=30, db_index=True)
needed_note = models.CharField(max_length=75, blank=True, null=True)
def __unicode__(self):
return "%s %s" % (self.player.name_first, self.player.name_last)
def percent_vote(self):
try:
return self.votes_received/float(self.ballots_cast)
except ZeroDivisionError:
return 0
Yes, it seems you can do something like this, but this may depend on the your database backend ( this should work for PostgreSQL ):
q = HallOfFame.objects.extra(select={'percent_vote_integer': "votes_received/ballots_cast", 'percent_vote_remainder': "votes_received%ballots_cast"})
q = q.extra(order_by = ['percent_vote_integer', percent_vote_remainder])
I ended up solving this issue with the code below. #Emil Davtyan's answer didn't work for me, and I wanted to figure out a more general solution.
def home(request):
hall = HallOfFame.objects.filter(inducted=True, voted_by='BBWAA')
hall_sorted = sorted(hall, key=lambda member: member.percent_vote, reverse=True)[:20]
return render_to_response('top_lists.html', {'hall': hall_sorted })
the model has this:
#property
def percent_vote(self):
try:
return float(self.votes_received)/self.ballots_cast
except ZeroDivisionError:
return 0

How can I remove duplicate objects in an order_by query?

>>> a = group.objects.order_by('groupname')
>>> print a
[<group: beginner 593785332>, <group: beginner 903647323>, <group: blbrz 229225098>]
I don't want to have objects with similar goupname, I want to have distinct groupname for each object:
[<group: beginner 593785332>, <group: blbrz 229225098>]
What can I do?
from django.db import models
class accounts(models.Model):
twitterid = models.IntegerField()
credit = models.IntegerField()
activate = models.TextField()
ban = models.TextField(blank=True)
others = models.TextField()
def __unicode__(self):
return u'%s' % (self.twitterid)
class Meta:
ordering = ['twitterid']
class group(models.Model):
groupname = models.TextField()
accounts=models.ForeignKey(accounts)
def __unicode__(self):
return u'%s %s' % (self.groupname, self.accounts)
If your database backend were PostgreSQL, you could do it with a queryset:
a = group.objects.order_by('groupname').distinct('groupname')
Unfortunately you are using SQLite, so you would preferably do it in python :
a = group.objects.order_by('groupname')
groupnames = set()
b = []
for item in a:
if a.groupname not in groupnames:
b.append(a)
groupnames.add(a.groupname)
a = b