Skip to content

Instantly share code, notes, and snippets.

@unpluggedcoder
Created December 22, 2017 03:05
Show Gist options
  • Save unpluggedcoder/6a63b18c513c7da49ae631109eada592 to your computer and use it in GitHub Desktop.
Save unpluggedcoder/6a63b18c513c7da49ae631109eada592 to your computer and use it in GitHub Desktop.
[limit_choices_to example for Django GenericForeignKey] limit model choice to specified model #Django #Python #GenericForeignKey
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
class Poll(models.Model):
question = models.CharField(max_length=500)
answers = # ...
# ...
limit = models.Q(app_label='your_app', model='page') | \
models.Q(app_label='your_app', model='article')
content_type = models.ForeignKey(
ContentType,
verbose_name=_('content page'),
limit_choices_to=limit,
)
object_id = models.PositiveIntegerField(
verbose_name=_('related object'),
)
content_object = generic.GenericForeignKey('content_type', 'object_id')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment