Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

141
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda