Denver
Denver

Reputation: 9

Multiple Django records for one user

I want to add multiple values for a user in Django. in that a user may have several records displayed. Records should belong to a specific user selected.

Models.py looks like :

 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 doesnt work either. It displays records to all patients but I want a specific patient/user selected. OneToOne will display for specific user but only once.

Views.py looks like:

 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')

And my template looks like :

 {% 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 %}

This works fine but i can only add one patient record and i want multiple for the same user. At the Django database it tells me theres a record for that user.

NB:/The user is also a patient. Asking for help ..>>

Upvotes: 0

Views: 411

Answers (1)

Bryant
Bryant

Reputation: 439

You have a one to one relationship in your model which means one user to one record.

change the relationship to Foreign Key so that multiple records can go to one user.

What you need to change it to:

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

and in the view you are querying all of the records which is not what you want.

Views.py

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

With this you are filtering all the records that belong to this user

Upvotes: 1

Related Questions