Thursday, May 31, 2018

one-to-one GenericRelation best practices

Hello! This is my first question, so please excuse any mistakes.

I'm using django 1.8 (working on migration to 2.0).

I need to implement a one-to-one generic relation. To illustrate suppose I have three classes, the first representing and abstract class in a store and the other specific products which need extra information:


AbstractProduct(models.Model):
    <fields here>
    sale = GenericRelation('Sales')
    class Meta:
        abstract = True

Books(AbstractProduct):
    <fields here>

Magazines(AbstractProduct):
    <fields here>


Now I need to create a models for 'Sales'. Each sale is of a specific product. Following https://docs.djangoproject.com/en/2.0/ref/contrib/contenttypes/#generic-relations I used:

class Sales(models.Model):
    <fields here>
    content_type = models.ForeignKey(...)
    object_id = models.PositiveIntegerField(...)
    content_object = GenericForeignKey('content_type', 'object_id')


My problem is that by using this approach whenever I do

>>> Books.objects.get(pk=1).sale

I get back a manager since django does not know it is a one-to-one relation. And it makes me think that maybe I'm approaching this in the wrong way.

My question is:
(a) is this design a good solution for this problem? Is there a better approach? Has anyone solved a similar problem in a better way?
(b) is there a way to create a generic One-To-One relation?

I'm open to answers pointing to good blogs/books/articles which give a more formal approach to this kind of design issue, if you know a good one.

Thanks in advance! Yours,

Vitor.


--
Vitor Quintanilha Barbosa

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAB-MUC7h4S32XE8nj7%2BtpeYdv%3DtH%3DQBX3ghx0rVxU%2BF0mTAakg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment