在Django中以一个视图访问两个应用

时间:2019-07-18 07:36:19

标签: python django django-models

我有一个带有两个应用程序的Django项目。第一个market/models.py包括市场类别和股票类别,后者跟踪在任何给定市场上买卖的所有股票,如下所示:

class Market(models.Model):
    title = models.CharField(max_length=50, default="")
    current_price = models.DecimalField(max_digits=5, decimal_places=2)
    description = models.TextField(default="")
    shares_yes = models.IntegerField(default=0)
    shares_no = models.IntegerField(default=0)
    b = models.IntegerField(default=100)
    cost_function = models.IntegerField(default=0)
    open = models.BooleanField(default=True)

    def __str__(self):
        return self.title[:50]

    def get_absolute_url(self):
        return reverse('market_detail', args=[str(self.id)])

class Share(models.Model):
    user = models.ForeignKey('users.CustomUser',
        on_delete=models.CASCADE,
        related_name='user_shares', 
        default=None)
    market = models.ForeignKey(
        Market, 
        on_delete=models.CASCADE,
        related_name='market_shares', 
        default=None)
    share = models.IntegerField(default=0)

    def __str__(self):
        return str(self.share)

    def get_absolute_url(self):
        return reverse('market_list') 

第二个应用程序user/models.py用于创建自定义用户,如下所示:

class CustomUser(AbstractUser):
    points = models.IntegerField(default=1000)

我要做的是:点击特定市场模板上的按钮后,代码将遍历该市场中所有拥有份额的用户,以增加/减去每个市场的价值从总得分中分享他们所拥有的份额(当用户拥有负份额时会发生相减,这意味着他们由于卖空而欠了份额)。那时每股的价值就是当前的市场价格。

这是我目前在markets/views.py中所拥有的(最后的HttpResponseRedirect仅是重新加载页面):

def resolve(request, pk):
    market = Market.objects.get(pk=pk)
    market_users = Share.objects.values('user')
    for user in market_users:
        target_user = CustomUser.objects.get(username=user)
        target_user.points += market.current_price * int(user.share)
    market.open = False
    market.save()
    return HttpResponseRedirect('/' + str(pk))

与此相关的一个问题(可能还有其他问题)是target_user的格式为<QuerySet [{'user': 1}, {'user': 1}]>,这意味着Django抛出错误CustomUser matching query does not exist

任何建议将不胜感激!

在评论中遵循Higor的建议进行更新:

我尝试了此操作,它不会引发错误,但是无法更新用户点:

def resolve(request, pk):
    market = Market.objects.get(pk=pk)
    market_users = Share.objects.all() 
    print(market_users) # gives "<QuerySet [<Share: 10>, <Share: 10>]>"
    for user in market_users.iterator():
        print(user) # gives "10 10"
        if user.market == pk:
            target_user = CustomUser.objects.get(username=user)
            target_user.points += market.current_price * user.share
            target_user.save()
    market.open = False
    market.save()
    return HttpResponseRedirect('/' + str(pk))

1 个答案:

答案 0 :(得分:0)

您在做错什么是在user对象中访问Share的方式。

from django.shortcuts import get_object_or_404


def resolve(request, pk):
    # if no Market with this pk raises a 404
    market = get_object_or_404(Market, pk=pk)
    # get shares for the specific market
    shares = Share.objects.filter(market_id=pk).select_related('user')
    print(shares) # gives "<QuerySet [<Share: 10>, <Share: 10>]>"
    for share in shares:
        target_user = CustomUser.objects.get(pk=share.user.pk)
        target_user.points += market.current_price * share.share
        target_user.save()
    market.open = False
    market.save()
    return HttpResponseRedirect('/' + str(pk))

您可以使用here之类的反向字符来代替URL的硬编码