Django - 查询检查多对多关系字段中的项

时间:2018-03-07 00:48:21

标签: python django

我有一个User和Deal模型,如下所示。用户模型有一个“收藏夹”字段,与交易模型有多对多的关系。

我正在尝试允许用户将交易保存到收藏夹中。我已经测试了favoriteremove_favorite两个视图,两者都正在完成他们应该做的事情。

这是我的问题 - 我的deal_detail.html页面上的条件语句检查页面上的当前交易是否是登录用户的最爱似乎没有工作。

{% if deal_detail in user.favorites %}

我只是很难绕过如何检查这个问题。

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(unique=True, error_messages={'unique':"This email has already been registered."})
    username = models.CharField(max_length=40, default='')
    first_name = models.CharField(max_length=40, default='', blank=True)
    last_name = models.CharField(max_length=40, default='', blank=True)
    date_joined = models.DateTimeField(default=timezone.now)
    favorites = models.ManyToManyField(Deal, related_name='favorited_by', null=True, blank=True)

class Deal(models.Model):
    title = models.CharField(max_length=200)
    slug = models.SlugField(max_length=140, unique=True)
    description = models.TextField(default='')

我的相应观点如下:

    def deal_by_detail(request, slug):
        deal_detail = Deal.objects.get(slug=slug)
        user = request.user
        return render(request, 'deals/deal_detail.html', {'deal_detail': deal_detail, 'user': user})

    @login_required(login_url='/accounts/sign_in/')
    def favorite(request, pk):
        if request.method == 'POST':
            favorite = Deal.objects.get(pk=pk)
            user = request.user
            user.favorites.add(favorite)
            messages.add_message(request, messages.INFO, 'Deal Favorited.')
            return redirect('home')

    @login_required(login_url='/accounts/sign_in/')
    def remove_favorite(request, pk):
        if request.method == 'POST':
            favorite = Deal.objects.get(pk=pk)
            user = request.user
            user.favorites.remove(favorite)
            messages.add_message(request, messages.INFO, 'Deal Removed.')
            return redirect('home')

我的表单deal_detail.html如下所示:

  {% if deal_detail in user.favorites %}

     <form id="favorite{{deal_detail.id}}" method="POST" action="{% url 'deals:favorite' deal_detail.id %}">
      {% csrf_token %}
       <input type="hidden" name="supporttype" />
       <input type="submit" value="Add Deal to Favorites" />
    </form>

     {% else %}

      <form id="favorite{{deal_detail.id}}" method="POST" action="{% url 'deals:remove_favorite' deal_detail.id %}">
      {% csrf_token %}
       <input type="hidden" name="supporttype" />
       <input type="submit" value="Remove Deal From Favorites" />
      </form>

{%endif%}

1 个答案:

答案 0 :(得分:1)

我相信你在很多人之后都错过了.all。然后它应该能够按预期运行检查和功能

{% if deal_detail in user.favorites.all %}