Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create a django model record using get_or_create and select_related

I have a class like below:

class GroupProduct(models.Model):
   product = models.ForeignKey(
           'myapp.Products'
           related_name='myapp_group_product')


   @classmethod
   def create_group_product(cls, p_id, product_id):
       cls.objects.get_or_create(id=p_id, defaults=dict(product=product_id).select_related('product')

So I expect it creates a record in the table with the following params, however it doesn’t.

GP = GroupProduct()
GP.create_group_product(3, 225)

It says it product must be a myapp.Products instance. Is there any way to use select_related in this way rather than doing a seprate query and hit the database?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can work with:

cls.objects.select_related('product').get_or_create(
    id=p_id,
    defaults={'product_id': product_id}
)

If the item already exists, it will fetch the product data with the same query. If it does not (yet) exists, it will make an insert query, and you can then fetch the Product in a second query, since it will not make any fetch query and thus simply create a record and return a cls object.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading