Created
June 10, 2015 13:57
-
-
Save aliev/b62f78e6f3112208cae6 to your computer and use it in GitHub Desktop.
Django and Content Types
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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