I have model like this:
class Kaart(models.Model):
name = models.CharField(max_length=200, verbose_name="Kaardi peakiri", help_text="Sisesta kaardi pealkiri (maksimum tähemärkide arv on 38)", blank=False, null=False)
url = models.CharField(max_length=200, blank=False, null=False, verbose_name="Asukoha URL", help_text="Täisasukoht (http://www.domeen.ee/kaart/)")
kirjeldus = models.TextField(max_length=500, verbose_name="Kommentaar", help_text="Informatsioon / viide tegijale (mitte kohustuslik)")
开发者_如何学JAVA date_added = models.DateField(help_text="lisamis kuupäev", verbose_name="Kuupäev", blank=False, null=False, default=datetime.date.today())
neg = models.PositiveIntegerField(default=0)
pos = models.PositiveIntegerField(default=0)
def diff(self):
return self.pos - self.neg
my view - notice the commented out part:
def index(request):
#a = Kaart.objects.all()
a = Kaart.objects.all().order_by('diff')
return render_to_response('index.html', {
'k':a,
}, context_instance=RequestContext(request))
and template:
{% for kaart in k %}
<tr>
<td class="tc"><span class="nr">1</span></td>
<td>
<a href="#">{{ kaart.name }}</a>
<a href="{{ kaart.url }}" id="full-url" title="k.kirjeldus">URL</a>
</td>
<td class="tc">{{ kaart.shortdate }}</td>
<td class="tr">
<span class="pos">{{ kaart.diff }}</span>
<a href="#"><img src="hinda/img/thumbs-up.jpg" /></a>
<a href="#"><img src="hinda/img/thumbs-down.jpg" /></a>
</td>
</tr>
{% endfor %}
And the error i get is: Caught an exception while rendering: Cannot resolve keyword 'diff' into field. Choices are: date_added, id, kirjeldus, name, neg, pos, url.
highlighted row is
{% for kaart in k %}
interesting thing is that when i comment in the part thats commented out atm and comment out sorted queryset then everything is working fine. Whats wrong here?
how can i get this query sorted by diff?
Alan.
You will have to do it like this I believe:
a = Kaart.objects.all().extra(
select = {'diff': 'pos - neg'}
).order_by('diff')
The order_by
arguments must be resolvable by the SQL interpreter in your database. Your diff
method is in Python, and so isn't available at the SQL level. Baresi's answer looks good.
精彩评论