Django GenericForeignKey being deleted when it shouldn't

147 Views Asked by At

I'm having a problem where if I delete an object, another object is being deleted seemingly wrongly.

models.py

class Document(models.model):
    file = models.FileField(upload_to=document_path, null=True, max_length=256)
    ri_ct = models.ForeignKey(
        ContentType, null=True, editable=False, related_name='documents_related_item', on_delete=models.PROTECT
    )
    ri_id = models.PositiveIntegerField(null=True, editable=False, db_index=True)
    related_item = GenericForeignKey('ri_ct', 'ri_id')


class Invoice(models.model):
    documents = GenericRelation(
        Document, related_query_name='invoices', content_type_field='ri_ct', object_id_field='ri_id'
    )


class BalanceUpdate(models.model):
    related_item_ct = models.ForeignKey(
        ContentType,
        limit_choices_to=Q(app_label='main', model__in=('proformainvoice', 'invoice')),
        related_name='balance_updates',
        null=True,
        on_delete=models.PROTECT,
    )
    related_item_id = models.PositiveIntegerField(null=True, blank=True, db_index=True)
    related_item = GenericForeignKey(ct_field='related_item_ct', fk_field='related_item_id')

Now, if I do

Invoice.objects.filter(query).delete()

I'm getting a BalanceUpdate, which is related to Invoice, also deleted.

After a fair amount of debugging I've found that when deleting the Invoice, the document is being deleted (correctly due to the defined GenericRelation).

If we look at Collector.collect we have a recursive function which collects the objects to be deleted.

If I insert a print here, when the model is Document, sub_objs contains the BalanceUpdate object. How can this be the case? The Document obj surely should have sub_objs containing a BalanceUpdate, they are seemingly not linked?

Cheers in advance.

0

There are 0 best solutions below