Ticket #13137: foobar_models.py

File foobar_models.py, 1.7 KB (added by Justin de Vesine, 15 years ago)

Code and instructions to reproduce

Line 
1## file: foobar/models.py
2from django.db import models
3from django.contrib.contenttypes.models import ContentType
4from django.contrib.contenttypes import generic
5
6class TaggedItem(models.Model):
7 tag = models.SlugField()
8 content_type = models.ForeignKey(ContentType)
9 object_id = models.PositiveIntegerField()
10 content_object = generic.GenericForeignKey('content_type', 'object_id')
11
12
13class Person(models.Model):
14 first_name = models.CharField(max_length=30)
15 last_name = models.CharField(max_length=30)
16
17
18# Before using, make sure that django_content_type contains a row like:
19# +----+--------+-----------+--------+
20# | id | name | app_label | model |
21# +----+--------+-----------+--------+
22# | 0 | person | foobar | person |
23# +----+--------+-----------+--------+
24# Do this as follows, after syncdb:
25# sql> update django_content_type set id = 0 where app_label="testapp" and model="person";
26
27# # Create a Person:
28# In [1]: from foobar.models import TaggedItem, Person
29#
30# In [2]: bob = Person(first_name="bob", last_name="bobberson")
31#
32# In [3]: bob.save()
33#
34# # Tag the person:
35# In [4]: tag = TaggedItem(tag="bob tag", content_object=bob)
36#
37# In [5]: tag.save()
38#
39# # Try to retrieve the person:
40# In [6]: fetchtag = TaggedItem.objects.get(id=tag.id)
41#
42# # content_object is None?
43# In [7]: fetchtag.content_object is None
44# Out[7]: True
45#
46# # But the object ID is correct...
47# In [8]: fetchtag.object_id == bob.id
48# Out[8]: True
49#
50# # And so is the content_type...
51# In [9]: fetchtag.content_type
52# Out[9]: <ContentType: person>
53#
54# # And we can get the model_class for that content type.
55# In [10]: fetchtag.content_type.model_class()
56# Out[10]: <class 'foobar.models.Person'>
Back to Top