我一直试图让这个查询工作几个小时,我很乐意帮助,因为我还是Django的新手。
我有这些模型(简化)
class Job(models.Model):
country = models.ForeignKey(Country)
active = models.BooleanField()
class Country(models.Model):
name = models.CharField(max_length=100)
class State(models.Model):
name = models.CharField(max_length=100)
country = models.ForeignKey(Country)
class City(models.Model):
name = models.CharField(max_length=100)
state = models.ForeignKey(State)
class Worker(models.Model):
name = models.CharField(max_length=100)
addresses = models.ManyToManyField(Address)
class Address(models.Model):
address_field = models.CharField(max_length=100)
city = models.ForeignKey(City)
我想在我的工人有一个地址的所有国家/地区选择所有不同的和有效的工作。我的观点有这段代码:
def get(self, request):
worker = Worker.objects.get(pk=request.user.id)
full_query = Q(active=True)
# my problem is here, since it is a ManyToMany Relationship
full_query &= Q(country__id__in=worker.addresses ??????)
jobs = Job.objects.filter(full_query)
我认为这样可以在for循环中获取所有工作人员的地址,并将国家/地区ID保存在列表中并执行
country_ids = []
for address in worker.addresses:
country_ids.append(address.city.state.country.id)
Q(country__id__in=[country_ids])
但我认为Django有更优雅的方式。
提前致谢!
答案 0 :(得分:0)
尝试
jobs = Job.objects.filter(active=True).filter(country__state__city__address__in=worker.addresses.all())