Home > Enterprise >  Django: To combine and retrieve rows from different models
Django: To combine and retrieve rows from different models

Time:03-12

1.We have two similar models, and I would like to be able to retrieve these at the same time and sort them by posting date and time, etc. Is it possible?

2.Or should both redundant fields be combined into one model?

# 1.
class Model1(models.Model):
    title = ...
    thumbnail = ...
    description = ...
    ...

class Model2(models.Model):
    title = ...
    image_url = ...
    product_id = ...
    reivew = ...


# 2. Combine into one model
class Model(models.Model)
    title = ...
    thumbnail = ...
    description = ...
    image_url = ...
    product_id = ...
    reivew = ...

CodePudding user response:

You can union() two models with no shared parents, and after that order_by() some column.

CodePudding user response:

'Consider this answer from a beginner'
If you just want to fetch someones model1 and model2 objects with just one query statement maybe is good to inherit two models from a base model like this:
in your models.py:

class Base(models.Model):
    title = ...
    created_at = models.DateTimeField(auto_now_add=True)
    owner = models.ForeignKey(user)
    
    class Meta:
        ordering = ['-created_at'] 

# inherits fields of Base model
class Model1(Base):
    field = ...
    # fields

class Model2(Base):
    # fields

using this method, remember fill needed fields of `Base' model like this:

>>> m1 = Model1(field="value", title=..., owner=UserObject,...).save()
# for get objects do normal:
>>> objects = Base.objects.filter(owner=user)
# the result is list of users `Model1' or 'Model2` created objects

Also you can use django-model-utils and get Base objects by child type. It would be like this:

from model_utils.managers import InheritanceManager
 
class Base(models.Model):
    # like previous version
    # just remember modify objects
    objects = InheritanceManager()

# inherits fields of Base model
class Model1(Base):
    
class Model2(Base):
    

get objects:

>>> Base.objects.all().select_related('Model1', 'Model2')

please read also this answer and others.

  • Related