ForeignKey with different queryset from manager

33 views
Skip to first unread message

Jimmy Gawain

unread,
Dec 14, 2020, 5:44:25 PM12/14/20
to Django users
This is with Django v2.2.

We use tombstoning via a custom BaseModelManager to mark items as deleted in the database but keep them around for reference.

class BaseModelManager(models.Manager):
    def __init__(self, *args, **kwargs):
        self.include_tombstoned = kwargs.pop('include_tombstoned',False)
        super(BaseModelManager, self).__init__(*args, **kwargs)

    def get_queryset(self):
        if not self.include_tombstoned:
            return TombstonedQuerySet(self.model).filter(is_tombstoned=False)
        return TombstonedQuerySet(self.model)

class BaseModel(models.Model):
    def __init__(self, *args, **kwargs):
        super(BaseModel, self).__init__(*args, **kwargs)

    # manager
    objects = BaseModelManager()
    all_objects = BaseModelManager(include_tombstoned=True)

This way models can reference Model.objects when they want undeleted items and Model.all_objects when they want to included deleted items.

We now have a situation where we want a ForeignKey, which uses objects, to use all_objects instead.

That is instead of this:

ref_member = models.ForeignKey(Member, related_name='+', null=True, blank=True, on_delete=models.CASCADE)

Do something like this:

ref_member = models.ForeignKey(Member, queryset=Member.all_objects.all(), related_name='+', null=True, blank=True, on_delete=models.CASCADE)

Is there any way to do the equivalent of this?

thanks

Peter of the Norse

unread,
Jan 10, 2021, 8:51:25 PM1/10/21
to django...@googlegroups.com
This is an interesting question.  Thank you for asking it.

I wasn’t able to find exactly what you are asking for.  The closest I could find was https://docs.djangoproject.com/en/2.2/topics/db/queries/#using-a-custom-reverse-manager which needs to be invoked at the call.  So you you have to do. 

parent.member_set(manager=‘all_objects').all()

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/4ee488b1-3489-430d-b917-70c157b35a92n%40googlegroups.com.

Reply all
Reply to author
Forward
0 new messages