【问题标题】:Multiple Django records for one user一个用户的多个 Django 记录
【发布时间】:2020-11-18 13:10:23
【问题描述】:

我想在 Django 中为用户添加多个值。因为用户可能会显示多条记录。 记录应属于选定的特定用户。

Models.py 看起来像:

 class Medrecs(models.Model):
    user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
    title = models.CharField(max_length=60, null=True)
    clinician = models.ForeignKey(Clinician, on_delete=models.PROTECT)
    Patient = models.ForeignKey(Patient, on_delete=models.CASCADE)
    meds = models.TextField()
    
    def __str__(self):
        return self.title

models.ForeignKey 也不起作用。它向所有患者显示记录,但我希望选择特定的患者/用户。 OneToOne 将为特定用户显示,但仅显示一次。

Views.py 看起来像:

 def my_profile(request):
    meds = Medrecs.objects.all()
    if request.user.is_authenticated:
        return render(request, 'MyDoc/my_profile.html', {'meds': meds})
    else:
        return redirect('MyDoc:login_patient')

我的模板看起来像:

 {% if meds %}
        {% for m in meds %}
<div class="col-sm-6 panel-primary">
<img class="logo" style="height: 35px; width: 35px; margin-right: 15px;" src="{{ user.patient.image.url }}">
    <p>St.Denvers Hospital,</p><br>
    <p>Healthcare is our compassion</p>
    <p>{{ m.title }}</p>
    <div class="panel panel-primary">
        <div class="panel-heading active">
            <h3 class="text-success">Doctor:{{ m.clinician }}</h3>
            <p>Name: {{ m.patient }}</p>
        </div>

        <div class="panel-body">
            <p>Medication: {{ m.meds }}</p>
        </div>
    </div>
</div>
        {% endfor %}
{% endif %}

这很好用,但我只能添加一个患者记录,并且我想为同一用户添加多个。在 Django 数据库中,它告诉我该用户有一条记录。

NB:/用户也是患者。 寻求帮助..>>

【问题讨论】:

    标签: python django


    【解决方案1】:

    您的模型中有一对一的关系,这意味着一个用户对一个记录。

    将关系更改为外键,以便多个记录可以转到一个用户。

    您需要将其更改为:

    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="records")

    在视图中,您正在查询所有不是您想要的记录。

    Views.py

    if request.user.is_authenticated:
        meds = Medrecs.objects.all().filter(user=request.user)
        return render(request, 'MyDoc/my_profile.html', {'meds': meds})
    

    这样,您将过滤属于该用户的所有记录

    【讨论】:

      猜你喜欢
      • 2013-02-15
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-12
      相关资源
      最近更新 更多