如何在ManyToMany Django中获取数据并在view.py中渲染

时间:2019-03-10 14:42:48

标签: django

我想将数据提取到我的view.py中,买方在其中选择特定的市场。这意味着买方只能看到他选择的市场。

class Market(models.Model):
    name = models.CharField(max_length=30)
    address = models.TextField("Market Address")
    interval = models.PositiveIntegerField("Market Day Interval", default=5)
    startdate = models.DateField("Initial Date", auto_now=False, auto_now_add=False) 
    location = models.ForeignKey(Local, related_name='market_location', on_delete=models.CASCADE)
    desciption = models.TextField("Good Description")
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name



class Buyer(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
    market = models.ManyToManyField(Market, related_name='interested_markets')
    status = models.BooleanField("User Status", default=False)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)


    def __str__(self):
        return self.user.username

view.py

@login_required
@buyer_required
def welcome_buyer(request): 
    buyer = request.user.buyer
    market = buyer.interested_markets.all()


    return render(request, 'buyer/home.html', {
    'market': market
    }) 

1 个答案:

答案 0 :(得分:0)

您可以使用买方对象简单地对此进行迭代:

for market in buyer.market_set.all()

markets = buyer.market_set.all()

在您的情况下为:

markets = buyer.interested_markets_set.all()

markets = buyer.market # you should consider changing it's name to be plural to indicate that it's a list of objects like: buyer.markets

有关更多详细信息,请阅读此处的文档:django many to many