1 from django.db import models
5 # Some monkey patches to EAV:
8 eav.models.slugify = lambda x: x
10 # Allow more characters
11 eav.models.BaseSchema._meta.get_field_by_name("name")[0].max_length = 200
13 from django.contrib.auth.models import User
14 from django.contrib.contenttypes.generic import GenericRelation, GenericForeignKey
15 from django.contrib.contenttypes.models import ContentType
17 from lxml import etree
18 from dcmeta.utils import RDFNS, common_prefixes, NamespaceDescriptor
21 logger = logging.getLogger("django.dcmeta")
23 class Description(eav.models.BaseEntity):
24 """Collection of meta-data that can be assigned to an entity."""
25 object_id = models.PositiveIntegerField(blank=True, null=True)
26 content_type = models.ForeignKey(ContentType, blank=True, null=True)
28 about = GenericForeignKey()
29 about_uri = models.TextField()
31 attrs = GenericRelation('Attr', object_id_field="entity_id", content_type_field="entity_type")
33 # shortcuts to EAV attributes
34 dublincore = NamespaceDescriptor('http://purl.org/dc/elements/1.1/')
35 marcrel = NamespaceDescriptor('http://www.loc.gov/loc.terms/relators/')
38 def get_schemata_for_model(self):
39 return Schema.objects.all()
42 def import_rdf(cls, text):
43 doc = etree.fromstring(text)
44 xml_desc = doc.xpath('/rdf:RDF/rdf:Description', namespaces={"rdf": RDFNS.uri})
47 raise ValueError("Invalid document structure.")
49 xml_desc = xml_desc[0]
51 desc = Description.objects.create(about_uri=xml_desc.get(RDFNS("about")))
53 for xml_property in xml_desc.iterchildren():
54 property, _created = Schema.objects.get_or_create(
55 name=xml_property.tag, datatype=Schema.TYPE_TEXT)
56 property.save_attr(desc, xml_property.text)
58 desc = Description.objects.get(pk=desc.pk)
61 def __getitem__(self, key):
62 if not isinstance(key, tuple):
66 if ns in common_prefixes: # URI given, value stored as prefix
67 ns = common_prefixes[ns]
69 return getattr(self, "{%s}%s" % (ns, attr))
71 def __setitem__(self, key, value):
72 return setattr(self, "dc_" + key, value)
74 class Schema(eav.models.BaseSchema):
77 class Choice(eav.models.BaseChoice):
79 For properties with multiply values.
81 schema = models.ForeignKey(Schema, related_name='choices')
83 class Attr(eav.models.BaseAttribute):
84 schema = models.ForeignKey(Schema, related_name='attrs')
85 choice = models.ForeignKey(Choice, blank=True, null=True)