1 from django.contrib.contenttypes import generic
2 from django.contrib.contenttypes.models import ContentType
3 from django.db import models
5 from philo.models.base import value_content_type_limiter, register_value_model
6 from philo.utils import fattr
9 __all__ = ('Collection', 'CollectionMember')
12 class Collection(models.Model):
14 Collections are curated ordered groupings of arbitrary models.
17 #: :class:`CharField` with max_length 255
18 name = models.CharField(max_length=255)
19 #: Optional :class:`TextField`
20 description = models.TextField(blank=True, null=True)
22 @fattr(short_description='Members')
24 """Returns the number of items in the collection."""
25 return self.members.count()
27 def __unicode__(self):
34 class CollectionMemberManager(models.Manager):
35 use_for_related_fields = True
37 def with_model(self, model):
39 Given a model class or instance, returns a queryset of all instances of that model which have collection members in this manager's scope.
43 >>> from philo.models import Collection
44 >>> from django.contrib.auth.models import User
45 >>> collection = Collection.objects.get(name="Foo")
46 >>> collection.members.all()
47 [<CollectionMember: Foo - user1>, <CollectionMember: Foo - user2>, <CollectionMember: Foo - Spam & Eggs>]
48 >>> collection.members.with_model(User)
49 [<User: user1>, <User: user2>]
52 return model._default_manager.filter(pk__in=self.filter(member_content_type=ContentType.objects.get_for_model(model)).values_list('member_object_id', flat=True))
55 class CollectionMember(models.Model):
57 The collection member model represents a generic link from a :class:`Collection` to an arbitrary model instance with an attached order.
60 #: A :class:`CollectionMemberManager` instance
61 objects = CollectionMemberManager()
62 #: :class:`ForeignKey` to a :class:`Collection` instance.
63 collection = models.ForeignKey(Collection, related_name='members')
64 #: The numerical index of the item within the collection (optional).
65 index = models.PositiveIntegerField(verbose_name='Index', help_text='This will determine the ordering of the item within the collection. (Optional)', null=True, blank=True)
66 member_content_type = models.ForeignKey(ContentType, limit_choices_to=value_content_type_limiter, verbose_name='Member type')
67 member_object_id = models.PositiveIntegerField(verbose_name='Member ID')
68 #: :class:`GenericForeignKey` to an arbitrary model instance.
69 member = generic.GenericForeignKey('member_content_type', 'member_object_id')
71 def __unicode__(self):
72 return u'%s - %s' % (self.collection, self.member)
78 register_value_model(Collection)