Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

128
Vistas
DRF changing field name values of django models with foreign keys

I followed suggestion from this question But i need to name one field of query_set to date filed of another object

My models are

class Choice(models.Model):
    question = models.ForeignKey(Question, related_name='choice', on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

    def __str__(self):
        return self.choice_text


class ChoiceWithTime(models.Model):
    choiceTime = models.ForeignKey(Choice,related_name='choiceTime', on_delete=models.CASCADE)
    choice_date=models.DateField()

My view

class QuestionChoicesViewSet(viewsets.ModelViewSet):
    queryset = Choice.objects.all()
    serializer_class = ChoiceDateSerializer

    def get_queryset(self):
        return Choice.objects.values('choiceTime__choice_date','choice_text').annotate(
            total_votes=Count('choiceTime__choice_date'),
        )

I need to count number of submission in particular dates

I don't know how to name choiceTime__choice_date that serializer recognizes field in query set

class ChoiceDateSerializer(serializers.ModelSerializer):
    choiceTime__choice_date  = serializers.DateTimeField()
    total_votes = serializers.IntegerField()

    class Meta:
        model = Choice
        fields = ('id', 'choice_text','total_votes','choiceTime__choice_date')

i receive

{
    "choice_text": "ant tower",
    "total_votes": 3,
    "choiceTime__choice_date": "2017-04-20"
}

But i want to recieve

{
    "choice_text": "ant tower",
    "total_votes": 3,
    "choice_date": "2017-04-20"
}

Tried different options with no success. Definitely i am missing the point. For my purposes it is working, but i want to have well written API.

2 option change time submission model?

class ChoiceWithTime(models.Model):
    choiceTime = models.ForeignKey(Choice,related_name='choiceTime', on_delete=models.CASCADE)
    choice_date=models.DateField()
    coutner = models.IntegerField(default=0)

Is 2 option considers to be better approach to my particular problem? Thanks!

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

You are receiving a json object, which you add its key value.

 for vote_detail in data:
   if vote_detail.choiceTime__choice_date:
      vote_detail.choice_date=vote_detail.choiceTime__choice_date

then serialize and save, a quick solution.

You could also add to your model the name that you want to call it. That's closer to backend and maybe worth delving into.

over 4 years ago · Santiago Trujillo Denunciar

0

from django.db.models import Count,F

If anybody finds this problem and this is easiest answer i came up to. As it was suggested before passing to serializer change value using model package functions

class QuestionChoicesViewSet(viewsets.ModelViewSet):
    queryset = Choice.objects.all()
    serializer_class = ChoiceDateSerializer
    def get_queryset(self):
        return Choice.objects.all().annotate(choice_date=F('choiceTime__choice_date')).values('choice_date','choice_text').annotate(
            total_votes=Count('choiceTime__choice_date'),
        )
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda