Django dynamically choose a foreign key relation model

1.8k views Asked by At

I have a Comment model that I've been using for the News model:

class Comment(models.Model):
    news = models.ForeignKey(News, on_delete=models.CASCADE)
    posted_by = models.ForeignKey(Student, on_delete=models.CASCADE)
    content = models.TextField(max_length=2048)
    posted_on = models.DateTimeField(auto_now_add=True)
    edited = models.BooleanField(default=False)
    last_edited_on = models.DateTimeField(auto_now=True)


    def __str__(self):
        return '{} - {}'.format(self.posted_by, self.news)

But now I have a Materials model and I want to have comments there too, but to use the same Comments model. Is there a way to dynamically choose the foreign key relation (news = models.ForeignKey(...) -> news_or_material = ... or something like this).

Of course I can write a separate model (MaterialComment), but I want to reuse my code.

Then in my viewset I should do something like this (I am using Django REST Framework):

def create(self, request, news_pk=None):
    news = get_object_or_404(News, id=news_pk)
    context = {'request': request, 'news': news}

    serializer = self.get_serializer_class()(
        context=context, data=request.data
    )
    serializer.is_valid(raise_exception=True)
    self.perform_create(serializer)
    headers = self.get_success_headers(serializer.data)

    return Response(
        serializer.validated_data,
        status=status.HTTP_201_CREATED,
        headers=headers
    )

I need to turn news_pk parameter from the URL to a pk of News or Material and respectively news_or_material = get_object_or_404(...)

1

There are 1 answers

0
Bipul Jain On

If you are developing this. Then it will wise to use GenericForeignKey provided by Django.

Generic Foreign Key Django