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

140
Vistas
How can I simplify retrieval of corresponding foreign key objects

I use Django on the backend and React on the frontend.

For example, I have quotes that are related to a character by foreign key. This is the Quotes model:

class Quotes(models.Model):
    quote = models.CharField(max_length=1000, unique=True, null=True, blank=False)
    quote_ja = models.CharField(max_length=1000, unique=True, null=True, blank=True)
    quote_by = models.ForeignKey(Characters, on_delete=models.SET_NULL, null=True, blank=True)
    quote_from = models.ForeignKey(Media, on_delete=models.SET_NULL, null=True, blank=True)
    date_added = models.DateField(auto_now=True)

I have some models with multiple foreign keys, for example in the above, quote_by returns the keys to the corresponding characters.

image of the foreign keys in api

This is the Characters Model connected to quote_by:

class Characters(models.Model):
    first_name = models.CharField(max_length=100, null=True, blank=False)
    last_name = models.CharField(max_length=100, null=True, blank=True)
    ja_name = models.CharField(max_length=100, null=True, blank=True)
    image = models.ImageField(upload_to='characters/', null=True, blank=True)

I would like to access the data from fields such as quote_by/quote_from with React. At the moment it seems overly complicated and I'm wondering if I should make a change to the backend.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

As far as I understand you are getting the IDs as Integer, instead, you wanted their related fields like first_name and last_name from Characters model to be callable from Quotes.

You don't have to modify your models here, however, you can achieve this by using Serializers. You can define the fields in the QuoteSerializer like this:

# that will populate the first_name from this related object. 
char_name = serializers.StringRelatedField(source='quote_by.first_name', read_only=True, many=False)

Sometimes StringRelatedField becomes complicated a bit. You can also define this as something like this.

char_name = serializers.CharField(source='quote_by.first_name', read_only=True,)

If you really want to put the logic into the models then you can create another field using the @property decorator. That will not create table in the db for that specific field. But can be used whenever you call it.

@property Also known as “managed attributes”, and a feature of Python since version 2.2. This is a neat way to implement attributes whose usage resembles attribute access, but whose implementation uses method calls. Source

For example:

class Quotes(models.Model):
    # ....
    @property
    def char_name(self):
        return self.quote_by.first_name + '' + self.quote_by.last_name

Now you simply get the char_name in serializer by defining as below:

char_name =  serializers.CharField(read_only=True,)
about 4 years ago · Juan Pablo Isaza 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