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

223
Visualizações
how do I manage deletion with multiple foreign keys to the same table in Django?

Say I have a model with a Things table and a table of relationships between the things called ThingRelations. It should not be possible to delete a Thing when there are ThingRelations that point to it. This is how I'm trying to implement that:

from django.db import models

class ThingRelation(models.Model):
    first_thing = models.ForeignKey('Thing', on_delete=models.PROTECT)
    second_thing = models.ForeignKey('Thing', on_delete=models.PROTECT)

class Thing(models.Model):
    name = CharField(max_length=260)

How do I automatically delete a Thing when there are no more ThingRelations pointing to it?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You have such options:

  • A routine. It can be made as a Command and something like crontab. Or it could be designed as a periodiq routine. This way you can repeatedly select all Thing models which have no relations with ThingRelation.
  • signals.py action. This way when entry of ThingRelation is deleted, you should check both the first_thing and second_thing in order to know whether the have any more ThingRelation relations pointing to them.
  • DB trigger (e.g. for PostgreSQL). The same idea as signal.py solution, but on DB level.

Which one should you choose? Depends on details of your exact objective. As for me, I use periodiq option on simple cases and DB trigger if I aim on high performance.

over 4 years ago · Santiago Trujillo 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