我有2个个人资料模型。我正在创建一个“参加者”对象。如何在两个配置文件之间进行过滤?
class Profile1(models.Model):
user = models.ForeignKey(User, null=True, unique=True)
class Profile2(models.Model):
user = models.ForeignKey(User, null=True, unique=True)
class Attendee(models.Model):
event = models.ForeignKey(Event)
# This filters through everything... How do I filter down just to the 2 profile objects?
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
profile = generic.GenericForeignKey('content_type', 'object_id')
感谢您的帮助!
答案 0 :(得分:8)
由于ContentType model有三个字段app_label
,model
和name
。因此,您可以轻松过滤这些字段。
attendees = Attendee.objects.filter(content_type__model = 'Profile1')
答案 1 :(得分:1)
我会去
from django.contrib.contenttypes.models import ContentType
...
Attendee.objects.filter(
content_type=ContentType.objects.get_for_model(Profile1))
避免在重构类名后比较字符串和错误。