2017-09-13 2 views
0

J'essaie de faire une requête django pour obtenir des messages ordre par VOTES - POST AGE.Django Recherche Requête comparant les votes et l'âge de poste avec Annoter

Exemple:

Messages normaux

1 - Hello World (10 votes) (Posted today) 
2 - Stackoverflow (12 votes) (Posted 2 days ago) 
3 - StackExchange (30 votes) (Posted 19 days ago) 

Alors, quand je filtre la requête par annoter, je veux ceci:

1 - StackExchange (30 votes - 19 days ago = 11 points) 
2 - Hello World (10 votes - 0 days ago = 10 points) 
3 - Stackoverflow (12 votes - 2 days ago = 10 points) 

J'essaie:

class DiffDays(Func): 
    function = 'DATEDIFF' 
    template = "%(function)s(%(expressions)s)" 


class CastDate(Func): 
    function = 'DATE_FORMAT' 
    template = "%(function)s(%(expressions)s, '%%%%Y-%%%%m-%%%%d')" 


list_posts = posts.extra(
    select={'pub_date': "DATE_FORMAT(pub_date,'%%%%Y-%%%%m-%%%%d')"} 
).annotate(
    diff_days=DiffDays(
     CastDate(today), F('pub_date')), output_field = DecimalField() 
).annotate(
    days_votes=ExpressionWrapper(
     F('n_votes') - F('diff_days'), output_field=IntegerField()) 
).order_by('days_votes') 

mais je reçois: 'IntegerField' object has no attribute 'resolve_expression'

Répondre

0

maintenant output_field à annoter pour diff_days est un argument de l'annoter, mais il faut être un argument de DiffDays, de sorte que votre besoin d'ajouter entre parenthèses pour le mettre dans func DiffDays

today = today.strftime('%Y-%m-%d') 

annotate(
    diff_days=DiffDays(
     (today, F('pub_date')), output_field=DecimalField()) 
     #^^^            ^^^ 
) 
+0

Je reçois ceci: 'séquence élément 0: instance str attendue, octets trouvés' –

+0

Comment avez-vous eu' today'? –

+0

'today = datetime.date.today()' –