A
A
Andrei1penguin12022-02-13 20:27:52
Django
Andrei1penguin1, 2022-02-13 20:27:52

How to organize multiple ForeignKeys in one Django model?

Good day, there is an image model that, let's say, can be used in a message, in a group and in a publication, something like this:

class Image(models.Model):
    group = models.ForeignKey("Group", on_delete=models.CASCADE, verbose_name="group", blank=True, null=True)
    publication = models.ForeignKey("Publication", on_delete=models.CASCADE, verbose_name="publication", blank=True, null=True)
    message = models.ForeignKey("Message", on_delete=models.CASCADE, verbose_name="message", blank=True, null=True)

When saving an image, the necessary argument is simply passed, for example, to save in a message:
Image.objects.create(message=some_message)
Or, for example, when saving in a group:
Image.objects.create(group=some_group)
There are no problems and everything works fine, but my question is:
Am I using the correct approach and is it normal that in each image at least two fields will be empty?
Whether it is competent from the point of use of the place in a DB and whether it is possible to make better?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrei1penguin1, 2022-02-14
@Andrei1penguin1

Still, my solution is one of the best and incomparably better in relation to the contenttypes framework proposed above
. Here is an interesting article that describes the cons of genericrelation and recommends one of the alternatives of my version:
https://pythobyte.com/avoid-django-s- genericforeig...

D
Dr. Bacon, 2022-02-13
@bacon

https://docs.djangoproject.com/en/4.0/ref/contrib/... although I would rather do it through ManyToManyField for the corresponding objects

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question