Skip to content

Instantly share code, notes, and snippets.

@aliev
Created June 10, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aliev/b62f78e6f3112208cae6 to your computer and use it in GitHub Desktop.
Save aliev/b62f78e6f3112208cae6 to your computer and use it in GitHub Desktop.
Django and Content Types
class FirstModel(models.Model):
pass
class SecondModel(models.Model):
pass
class BaseModel(models.Model):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
# Get by model
content_type = ContentType.objects.get_for_model(FirstModel)
# Get model class
model = content_type.model_class()
# ...
model.objects.all()
# Get by filtered object
content_type = ContentType.objects.get_for_model(FirstModel.objects.get(pk=1))
# Get by Model name
content_type = ContentType.objects.get(name='firstmodel')
# Get by Model id
content_type = ContentType.objects.get(pk=1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment