任何人都可以帮我解决一些相当复杂的Django查询吗?
这些是我的模特:
class County(models.Model):
name = models.CharField(max_length=100)
class Place:
id = models.IntegerField(primary_key=True)
county = models.ForeignKey(County)
class Translation(models.Model):
place = models.OneToOneField(Place,null=True)
county = models.ForeignKey(County) # Have denormalised for ease, but could delete this.
text = models.TextField()
user = models.ForeignKey(User, null=True, blank=True)
user_ip = models.IPAddressField()
created = models.DateField(auto_now_add=True)
如何运行以下查询?
我应该更改数据库设置以使其更容易吗?
谢谢!
答案 0 :(得分:3)
User.objects.all().annotate(Count('translation')).order_by('-translation__count')
County.place_set.filter(translation=None)
User.objects.all().filter(
translation__county__name="my_county"
).annotate(Count("translation")).order_by('-translation__count')[:5]