多对多和通过 table 的 Django 查询
Django query with many to many and through table
假设我有这些 Django ORM classes:
class Event(models.Model):
creator = models.ForeignKey(User, related_name="created_events")
participants = models.ManyToManyField(
User, related_name="joined_events", through='EventsParticipants')
class EventsParticipants(models.Model):
user = models.ForeignKey(User)
event = models.ForeignKey(Event)
date_invited = models.DateTimeField(
auto_now_add=True, blank=False, null=False)
class Meta:
unique_together = (('user', 'event'),)
class User(models.Model):
name = models.CharField(....)
我的问题是:
我想在单个查询集中获取我创建的所有事件 + 我使用事件 class 参与的所有事件。
像这样:
from django.db.models import Q
Event.objects.filter(Q(creator=me) | Q(participants=me)).distinct()
参见:
https://docs.djangoproject.com/en/1.9/topics/db/queries/#complex-lookups-with-q-objects
https://docs.djangoproject.com/es/1.9/ref/models/querysets/#django.db.models.query.QuerySet.distinct
假设我有这些 Django ORM classes:
class Event(models.Model):
creator = models.ForeignKey(User, related_name="created_events")
participants = models.ManyToManyField(
User, related_name="joined_events", through='EventsParticipants')
class EventsParticipants(models.Model):
user = models.ForeignKey(User)
event = models.ForeignKey(Event)
date_invited = models.DateTimeField(
auto_now_add=True, blank=False, null=False)
class Meta:
unique_together = (('user', 'event'),)
class User(models.Model):
name = models.CharField(....)
我的问题是: 我想在单个查询集中获取我创建的所有事件 + 我使用事件 class 参与的所有事件。
像这样:
from django.db.models import Q
Event.objects.filter(Q(creator=me) | Q(participants=me)).distinct()
参见:
https://docs.djangoproject.com/en/1.9/topics/db/queries/#complex-lookups-with-q-objects
https://docs.djangoproject.com/es/1.9/ref/models/querysets/#django.db.models.query.QuerySet.distinct