A
A
Andrei Ramanchyk2017-05-27 15:54:13
Django
Andrei Ramanchyk, 2017-05-27 15:54:13

When using objects,filter() when filtering by ForeignKey data, how to get data from the table that is from the model to which the link is?

There is a model

class ModuleWork(models.Model):
    module = models.ForeignKey(Module)
    module_number = models.ForeignKey(NumberModule)
    module_description = models.TextField()
    project = models.ForeignKey(Project)
    room = models.ForeignKey(Room)
    room_number = models.ForeignKey(NumberRoom)
    module_work_designation = models.CharField(max_length=20)
    executor = models.ForeignKey(User)
    module_work_is_produced = models.BooleanField()
    important = models.ManyToManyField(ImportantFeatures, blank=True)

    def __str__(self):
        return '{}-{}{}-{}{}'.format(self.project, self.room, self.module_number, self.module, self.module_number)

One of the views
class ModuleView(DetailView):
    model = ModuleWork
    template_name = 'module.html'

    def get_context_data(self, **kwargs):
        context = super(ModuleView, self).get_context_data(**kwargs)
        project_objectives = ProjectObjectives.objects.filter(module_work=self.kwargs['pk'])
        types_module = Module.objects.all()
        images = ImageModule.objects.filter(module_work=self.kwargs['pk'])
        image_main = ImageModule.objects.filter(module_work=self.kwargs['pk'], image_type=3)
        context['image_main'] = image_main
        context['images'] = images
        context['project_objectives'] = project_objectives
        context['types'] = types_module
        context['pk'] = self.kwargs['pk']  # Edit
        return context

    def get(self, request, *args, **kwargs):
        return super(ModuleView, self).get(request, *args, **kwargs)

The line from the code above
image_main = ImageModule.objects.filter(module_work=self.kwargs['pk'], image_type=3)

image_type is a foreignkey in the model.
How to make it filter not by image_type_id but by the test value from the table to which this field refers.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrei Ramanchyk, 2017-05-27
@jagrmi

If anyone is interested, I found my mistake, sorted out my problem
, turned to an example
, but I needed the
text in the code given for example

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question