I'd like to build a new related field type. Here's a simple example:
class CustomQuerySet(QuerySet):
def current(self):
return self.filter(invalid_date__isnull=True)
class CustomManager(Manager):
def get_query_set(self):
return CustomQuerySet(self.model, using=self._db)
def current(self):
return self.get_query_set().current()
class Item(models.Model):
objects = CustomManager()
row_id = models.IntegerField(primary_key=True)
id = models.IntegerField()
name = models.CharField(max_length=100)
change_date = models.DateTimeField(auto_now_add=True)
invalid_date = models.DateTimeField(null=True, blank=True)
class Collection(models.Model):
item = MultipleRelatedField(Item, related_field='id', related_name='collections')
name = models.CharField(max_length=100)
Given c = Collection()
:
c.item
should return a queryset equivalent toItem.objects.filter(id=c.item_id)
.- That queryset does need to be an instance of CustomQuerySet
Item.objects.filter(collections__name='SomeName')
should work as expected.- The operation
Collection.objects.filter(item__name='OtherName', item__invalid_date__isnull=True)
should work as expected.
I realize this could be implemented with a ManyToManyField
but I don't want to manually add/remove item objects to c.item. I don't need the join table as c.item always uses a single id value, it's just not a primary key on Collection. And c.item
may /not/ contain item objects with different id values.
I'm aware that this is likely going require subclassing django.db.models.fields.related.ForeignRelatedObjectsDescriptor
and/or django.db.models.fields.related.ForeignObject
(or possibly the ManyToMany equivalents).