Linking data to logged in authorized users

The survey app I am working on assigns a respondent_id and company_id to answers to teh questions.

Right now, I use the following code:

        respondent_id=request.user.id #Get user_id value as integer id
        company = request.user.groups.values_list('name',flat = True)# Get company for user logged in
        Comment.objects.create(comments = results_comments, respondent = respondent_id, company = company)

to identify the user. The Answer model is:

class Answer(models.Model):
    area = models.ForeignKey(
        Area, on_delete=models.CASCADE, null  = True 
    )
    value = models.IntegerField(null = True, blank=False)
    company=models.CharField(max_length=250, null = True)
    timestamp= models.TimeField(auto_now = True)
    question = models.ForeignKey(
        Question, on_delete=models.CASCADE, null  = True, unique=False
    )

    respondent = models.IntegerField(null = True, blank=False)
   

I understand I could use:

respondent_id = models.ForeignKey(settings.AUTH_USER_MODEL)

to get the logged in user_id to store with the data. Is there an advantage to that?

1 Like

Of course there many advantages to using a ForeignKey to the User model.

For example, you could easily access information in queries like so: Answer.objects.filter(respondent__username='jlc1978')

1 Like