根据usr django

时间:2017-12-07 03:31:12

标签: python django models favorites

我是Django的新手,我正在尝试创建一个最喜欢的应用程序。 我希望根据用户是否已经偏爱医生来更改喜欢的按钮。

我将医生和喜欢列表传递给我的模板,但不确定接下来要从数组中提取喜欢的内容,并且不确定这是否是最优雅的方法。

非常感谢任何帮助!

models.py

class Physician(models.Model):
    speciality = models.CharField(null=False, blank=False, max_length=30)
    first_name = models.CharField(null=False, blank=False, max_length=50)
    last_name = models.CharField(null=False, blank=False, max_length=50)
    title = models.CharField(null=False, blank=False, max_length=2)
    address1 = models.CharField(null=False, blank=True, max_length=50)
    address2 = models.CharField(null=True, blank=True, max_length=20)
    city = models.CharField(null=False, blank=False, max_length=50)
    state = models.CharField(null=False, blank=False, max_length=2)
    zip = models.CharField(null=False, blank=False, max_length=12)
    likes = models.IntegerField(default=1)


def __str__(self):
    template = '{0.last_name} {0.first_name} {0.speciality}'
    return template.format(self)

class Voter(models.Model):
    user = models.ForeignKey(User)
    physician = models.ForeignKey(Physician)

我的模板是  

    {% if physicians %} 
        {% for physician in physicians  %}
            <tr>
            <td> 
            <a href="/getmd/{{physician.id}}/">  
                {{ physician.last_name }}, {{ physician.first_name }} </a>
            </td>
            <td>{{ physician.state }}</td>
            <td>{{ physician.speciality }}</td>
            <td>{{ physician.id}}</td>
            <td><strong id="like_count{{physician.id}}">{{ physician.likes }}</strong> </td>
            <td> 
                {% if user.is_authenticated %}

                    {% if likedalready.physician].liked   %}

                        <button id="alreadyvoted" data-catid="{{physician.id}}" class="likes btn btn-secondary" type="button" title="Already faved">
                        <span class="glyphicon glyphicon-check"></span>
                        Faved
                        </button>
                    {%else%}
                        <button id="{{physician.id}}like" data-catid="{{physician.id}}" class="likes btn btn-primary" type="button" title="Fave Me">
                            <span class="glyphicon glyphicon-thumbs-up"></span>
                            Fav
                        </button>

                    {% endif %}

                {% endif %}

            </td>

            </tr>
        {% endfor %}


    {% else %}
    <p>Sign in to fave</p>
    {% endif %}
</tbody>

我的views.py def医生(请求):

user = User;
liked = False;
args = {}
args.update(csrf(request))
physicians = Physician.objects.all().order_by('last_name')

page = request.GET.get('page', 1)
paginator = Paginator(physicians, 10)
try:
    physicians = paginator.page(page)
except PageNotAnInteger:
    physicians = paginator.page(1)
except EmptyPage:
    physicians = paginator.page(paginator.num_pages)

#Create list of already liked physicians
return_list = []

for physician in physicians:
    liked = Voter.objects.filter(physician_id=physician.id, user_id=request.user.id).exists()
    return_list.append((physician, {'liked': liked}))

args['physicians'] = physicians    
return render(request, 'physicians.html', args, {'liked': return_list})

2 个答案:

答案 0 :(得分:0)

首先改变您的模型设计,

删除选民模型并在Physician模型中添加ManyToMany字段。同时从Physician模型

中删除likes属性
class Physician(models.Model):
    ....
    #users liked the physcian
    likers = models.ManyToManyField(User, related_name='liked_physicians')

views.py

context['physicians'] = Physician.objects.all().annotate(
    total_likes=Count('likers')
)

编写模板标签以检查(计数/存在)登录用户是否喜欢医生

@register.filter
def is_liker(physician, user):
    return physician.likers.filter(id=user.id).exists()

模板

{% for physician in physicians  %}

    {% if physcian|is_liker:request.user == True %} 
      liked
    {% else %}
      <button>Like</button>
    {% endif %}  

{% endfor %}

答案 1 :(得分:0)

我会有一个不同的模型,比如:

class Like(models.Model):
    user = models.ForeignKey(User)
    physician = models.ForeignKey(Physician)

该表将具有用户和医生之间的关系。 您可以知道用户是否喜欢医生。

Like.objects.filter(user=user, physician=physician).exists() 

如果用户不喜欢医生等,请删除该关系。

要获得用户喜欢的所有医生ID,您可以这样做:

physicians_liked = Like.objects.filter(user=user).values_list('physician', flat=True)

稍后您的模板就像检查一样简单:

{% if physician.id in physicians_liked %}
    ...
{% endif %}