rapidfields.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. def formfield(self, **kwargs):
  17. kwargs['form_class'] = RapidAlternativesField
  18. return super(GenericForeignKey, self).formfield(**kwargs)
  19. class AlternativeDataTables(models.ForeignKey):
  20. """
  21. Use an AlternativeDataTables model field on AlternativeData represetntations, instead of
  22. a ForeignKey with ContentTypes.
  23. """
  24. def __init__(self, alternatives=[], **kwargs):
  25. """
  26. Receives the same named parameters of a ForeignKey, but instead of a target table,
  27. receives a list of the tables that may keep the alternative data.
  28. :param alternatives: List of the tables that hold the alternative data.
  29. :param kwargs: Arguments to the ForeignKey, without a relationship target.
  30. """
  31. pks=[]
  32. try:
  33. pks = [ContentType.objects.get_for_model(a).pk for a in alternatives]
  34. except RuntimeError:
  35. #Querying ContentType within a content type is an issue at migrations
  36. pass
  37. kwargs['limit_choices_to'] = {'pk__in': pks}
  38. kwargs['to'] = ContentType
  39. super(AlternativeDataTables, self).__init__(**kwargs)
  40. self.alternatives = alternatives