在另一個標籤中使用多個欄位作為外鍵返回

2024-06-07 10:30:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Django新手,所以我做了3个简单的表来返回一个愿望列表。问题是,每当用户请求WishList时,他/她的user_id被用来进行SELECT查询来返回他/她自己的愿望列表。我想从我的WishList表中获取产品标题和产品url。我使用的是to_field,但用这种方法我只能拿回产品的标题。我对Django不太了解,帮帮我!在

产品

class Product(models.Model):
    class Meta:
        unique_together = (('id', 'title'),)
    title = models.CharField(max_length=200, unique=True,
                             help_text='Name of the product')
    url = models.CharField(max_length=300, default='',
                           help_text='Url of the product')

    def __str__(self):
        return 'Product: {}'.format(self.title)

愿望清单

^{pr2}$

Tags: djangoidurl标题列表产品titlemodels
1条回答
网友
1楼 · 发布于 2024-06-07 10:30:28

Django文档是您的朋友,read it。在

我是认真的,把documentation通读一遍。在

此外,将tou字段重写为另一个与您的字段不同的字段不是一个好的做法型号.pk除非你有一个很好的理由并且你知道你在做什么(绝对不是现在这样)。在

因此,在阅读文档之后,您将知道为了获得与用户相关的愿望,可以使用ForeignKey反向关系来获取用户的所有相关愿望列表。在

user_wishlists = my_user.wishlist_set.all()
#Because we know that you want to access the wishlist.products
#in order to optimize things (in terms of db queries)
#you can add and .select_related('product')
#e.g, user_wishlists = my_user.wishlist_set.all().select_related('product')

#now follow the wishlist.product foreign key to access the related product for every wishlist
for wishlist in user_wishlists:
    product = wishlist.product
    print (product.id, product.title, product.url)

现在,在您阅读了更多的文档之后 您将注意到您的WishList模型实际上是ManyToMany与他希望的产品之间的ManyToMany关系的{a3},然后您将知道您可以通过WishList在用户和产品之间定义一个M2M字段,如下所示:

^{pr2}$

相关问题 更多 >

    热门问题