我是Django的新手,所以我做了3个简单的表来返回一个WishList。事情是,我希望每当用户请求WishList时,他/她的user_id
被用来进行SELECT
查询以返回他/她自己的WishList。我想从我的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)
<标题> class WishList(models.Model):
class Meta:
unique_together = (('user', 'product'),)
user = models.ForeignKey(fbuser,
on_delete=models.CASCADE,
help_text='Facebook user',
to_field='user_id')
product = models.ForeignKey(Product, to_field='title', db_column='title',
on_delete=models.CASCADE)
def __str__(self):
return 'WishList: {}'.format(self.user)
标题>标题>
将to_field重写为与模型不同的另一个字段并不是一个好的做法。除非你有一个很好的理由,你知道你在做什么(绝对不是现在的情况)。
因此,在您阅读文档之后,您将知道为了获得与用户相关的愿望列表,您可以使用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
模型实际上是User
和他想要的产品之间的ManyToMany
关系的中间模型,然后你会知道你可以通过WishList
在用户和产品之间定义一个M2M字段,如下所示:
class FbUser(models.Model):
#...
wished_products = models.ManyToManyField(
Product,
through='WishList',
through_fields=('user', 'product')
)
#and now accessing user wished products would be easy as:
user_wished_products = my_user.wished_products.all()
for product in user_wished_products:
print (product.id, product.title, product.url)