如何在 Django 中使用 id 或 pk 检索数据

How to retrieve data using id or pk in django

我正在做一个项目,但在尝试了多种方法后仍然找不到解决方案。我需要在页面上获取当前房间,以便用户可以离开房间,我知道这与查询或使用 pk,id 有关。 (我的第一个问题,如果提问方式不正确,请见谅)。

这是来自 Views.py 的代码:


def leave_room(request, room):
    room = request.GET['room.pk']
    room_details = Room.objects.get(name=room)
    messages = Messages.objects.filter(room=room_details.pk)
    membership = RoomMember.objects.filter(user=request.user, room=messages)
    membership.delete()
    return redirect("/")

urls.py:

path("leave/<int:pk>/join/", views.leave_room, name="leave_room"),

html:

<a class="btn btn-danger" href="{% url 'leave_room' pk=room.pk %}">Leave Room</a>

models.py:

class Room(models.Model):
    name = models.CharField(max_length=100)
    about = models.TextField(max_length=500, null=True, blank=True)
    creator = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='room_creator')
    members = models.ManyToManyField(User, through="RoomMember")
    
    
class RoomMember(models.Model):
    approved = models.BooleanField(default=False, blank=False)
    room = models.ForeignKey(Room, related_name='memberships', on_delete=models.CASCADE)
    user = models.ForeignKey(User, related_name='user_groups', on_delete=models.CASCADE)
    
        
class Messages(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=False, blank=False)
    text = models.CharField(max_length=10000, blank=False, null=False)
    date = models.DateTimeField(default=datetime.now)
    room = models.ForeignKey(Room, null=True, blank=False, on_delete=models.CASCADE)

因为你有一个参数<int:pk>房间的主键是通过pk参数传递的。因此,这意味着 leave_room 应实现为:

from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_POST

@require_POST
@login_required
def leave_room(request, pk):
    nitems, __ = RoomMember.objects.filter(
        user=request.user, <strong>room_id=pk</strong>
    ).delete()
    if not nitems:
        raise Http404
    else:
        return redirect('<em>name-of-some-view</em>')

删除 link 因此是向视图发出 POST 请求的迷你形式:

<<strong>form method="post" action="{% url 'leave_room' pk=room.pk %}"</strong>>
    {% csrf_token %}
    <button type="submit" class="btn btn-danger">Leave Room</button>
</form>

Note: Section 9 of the HTTP protocol specifies that requests like GET and HEAD should not have side-effects, so you should not change entities with such requests. Normally POST, PUT, PATCH, and DELETE requests are used for this. In that case you make a small <form> that will trigger a POST request, or you use some AJAX calls.


Note: You can limit views to a view to authenticated users with the @login_required decorator [Django-doc].