views:

277

answers:

1

Hi there Stackers!

I have 2 models in question. JobRecord of which has many Activity(ies), the fk, of course, placed in the Activity model.

To aid data entry, I'd like to default the fk to JobRecord, within a new Activity, to the 'JobRecord fk of the last entered Activity, by the logged in User (bonus points!)'

Here's the model:

class Activity(models.Model):
    """
    Record multiple activities against a JobRecord
    """

    start               = models.TimeField(blank=True, null=True)
    end                 = models.TimeField(blank=True, null=True)
    job_record          = models.ForeignKey(JobRecord) # editable=False)
    task                = models.ForeignKey(Task, blank=True, null=True) # show only tasks found in project
    flora               = models.ManyToManyField(Species, blank=True, null=True, help_text='Optional subject flora.')

    memo                = models.TextField(blank=True, null=True)

    all_operators       = models.BooleanField(help_text="Check to include all operators from the parent job record")
    operators           = models.ManyToManyField(User, null=True, blank=True)

    duration            = models.DecimalField(blank=True, null=True, max_digits=7, decimal_places=2)

    class Meta:
        #order_with_respect_to = 'job_record' # not working?
        ordering = ['-job_record__date', 'job_record', 'start']

Thanks!

+1  A: 

As a very first step, you should store in some model the last activity for each user.

class ActivityLog(models.Model)
    user = models.ForeignKey(User)
    job_record = models.ForeignKey(JobRecord)

Then in the view, you can retrieve the activity by some simple query:

last_activity_data = ActivityLog.objects.filter(user=request.user)

and use it in initializing the form for the model:

form = ActivityForm(job_record=last_activity_data.job_record)

finally, remember to update the log when saving the Activity.

Note: I have omitted all error checking; for instance, you should take care of the case where there are no last_job_record's, but it should be quite trivial.

Finally, you could also use a ManyToManyField to the Activity, and then using Django's API; it would be perfectly equivalent (e.g., it would create a table very similar to this one behind the scenes), but I think the semantic would be slightly different and for this reason would I prefer the explicit solution.

Roberto Liffredo