rapidfields.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. from django.contrib.contenttypes.fields import GenericForeignKey
  2. from django.contrib.contenttypes.models import ContentType
  3. from rapid.rapidforms import RapidAlternativesField
  4. from django.db import models
  5. __author__ = 'marcos'
  6. """
  7. Model fields specific for Rapid Django.
  8. """
  9. class AlternativeData(GenericForeignKey):
  10. """
  11. A generic relation that Rapid will display as an inline form or a group of data at the
  12. edit and view actions.
  13. Create like a Django GenericForeignKey, but use an AlternativeDataTables instead of a
  14. ForeignKey to ContentTypes.
  15. """
  16. is_alternatives = True
  17. def formfield(self, **kwargs):
  18. kwargs['form_class'] = RapidAlternativesField
  19. return super(GenericForeignKey, self).formfield(**kwargs)
  20. class AlternativeDataTables(models.ForeignKey):
  21. """
  22. Use an AlternativeDataTables model field on AlternativeData represetntations, instead of
  23. a ForeignKey with ContentTypes.
  24. """
  25. is_alternatives = True
  26. def __init__(self, alternatives=[], **kwargs):
  27. """
  28. Receives the same named parameters of a ForeignKey, but instead of a target table,
  29. receives a list of the tables that may keep the alternative data.
  30. :param alternatives: List of the tables that hold the alternative data.
  31. :param kwargs: Arguments to the ForeignKey, without a relationship target.
  32. """
  33. pks=[]
  34. try:
  35. pks = [ContentType.objects.get_for_model(a).pk for a in alternatives]
  36. except RuntimeError:
  37. #Querying ContentType within a content type is an issue at migrations
  38. pass
  39. kwargs['limit_choices_to'] = {'pk__in': pks}
  40. kwargs['to'] = ContentType
  41. super(AlternativeDataTables, self).__init__(**kwargs)
  42. self.alternatives = alternatives