假设模型:
class User(models.Model):
name = models.CharField(max_length=32)
favorite = models.ForeignKey(Item)
class Item(models.Model):
name = models.CharField(max_length=32)
相应的Django是:
usersFavorites = User.objects.all().values_list("name", "favorite__name")
这并不使用你提供的田地的确切名称。 为此,您仅需要将这些模型添加适当的<代码>db_table和db_column
领域。
P.S. 这一特别图谋并不特别好。 IMHO,User
and Item
should have a many-to-many relationship:
class User(models.Model):
name = models.CharField(max_length=32)
favorites = models.ManyToManyField(Item, related_name="users")
class Item(models.Model):
name = models.CharField(max_length=32)
除非项目只有一个用户,在这种情况下是<代码>。 外国Key 项目代码>。
之后,你可以翻一番:
for user in User.objects.all().select_related("favorites"):
for favorite in user.favorites:
# use `user` and `favorite` in some way.
Because of the select_related()
call, the query is done in one fell swoop in the first for
loop.