Skip to content
Advertisement

django getting all objects from select

I also need the field (commentGroupDesc) from the foreign keys objects.

models.py

class commentGroup (models.Model):
    
        commentGroup = models.CharField(_("commentGroup"), primary_key=True, max_length=255)
        commentGroupDesc = models.CharField(_("commentGroupDesc"),null=True, blank=True, max_length=255)
    
        def __str__(self):
            return str(self.commentGroup)
        
        class Meta:
            ordering = ['commentGroup']
    
    class Comment (models.Model):
    
        commentID = models.AutoField(_("commentID"),primary_key=True)
        commentUser = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
        commentGroup = models.ForeignKey(commentGroup, on_delete=models.CASCADE,  null=True)
        commentCI = models.ForeignKey(Servicenow, on_delete=models.CASCADE,  null=True)
        commentText = RichTextField(_("commentText"), null=True, blank=True)
        commentTableUpdated = models.CharField(_("commentTableUpdated"), null=True, blank=True, max_length=25)
    
        def __str__(self):
            return str(self.commentGroup)
        
        class Meta:
            ordering = ['commentGroup']

views.py

comment = Comment.objects.get(pk=commentID)

Here I get the commentGroup fine but I also need commentGroupDesc to put into my form.

Advertisement

Answer

At first, it’s not a good thing to name same your model field as model name which is commentGroup kindly change field name, and run migration commands.

You can simply use chaining to get commentGroupDesc, also it’s better to use get_object_or_404() so:

comment = get_object_or_404(Comment,pk=commentID)

group_desc = comment.commentGroup.commentGroupDesc

Remember to change field and model name first.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement