Home > OS >  Creating a field in a model that allows multiple entries that is saved to the DB incrementally
Creating a field in a model that allows multiple entries that is saved to the DB incrementally

Time:03-09

I have a model called Handoff, users create a new handoff everyday and will add notes to this handoff to pass over to the next shift.

I need a field that can capture user entry and save to the DB, but this field needs to be able to write to the database iteratively. For context, the user will add a new note each time they have something to add to the handoff and this needs to be written to the DB individually (for example, if the field was called new_note, the data should write to the DB and each new note will be saved as new_note_1).

These notes will then be collated in a table to present to the next shift during a handoff.

What are the best methods for approaching this?

CodePudding user response:

The obvious answer is a HandoffEntry model with a TextField and a Foreign key to the related Handoff

class HandoffEntry (models.Model):
    handoff = models.ForeignKey( Handoff, models.CASCADE, related_name='entries', ...)
    text = models.TextField( ...)
    # and maybe a date-time-field with auto-update=True might be useful?

To display

handoff = Handoff.objects.get( ...) 
entries = handoff.entries.all().order_by('-pk') # most recent first, pk is unconditionally greater for newer

In a template you can iterate

{% for entry in entries %} 
    {{ entry.text }}
{% endfor %}

for data-entry, just a ModelForm with the one field text.

You could also auto-record who is doing the handoff into another field taking the data from request.user, or use another ForeignKey to User

CodePudding user response:

I think you need to start learning about Model Relationships. Django Documentation

You will want to try to create a model like below :

from django.db import models

class Note(models.Model):
    content = models.CharField(max_length=30)

    def __str__(self)
        return 'new_note_{}'.format(self.id)

class Handoff(models.Model):
    note = models.ForeignKey(Note, on_delete=models.CASCADE)

You can create the logic to create and save the note first, then attached the created model to the handoff model like below.


# something...

new_note = Note(
    content="Some Text"
)

new_note.save()

new_handoff = Handoff(
    note=new_note
)

new_handoff.save()

And there you have it, your model is now implemented and each new handoff has its unique one-to-one relationship with your handoff model.

  • Related