Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 976
schedulingqs Avatar asked Jan 26 '26 13:01

schedulingqs


1 Answers

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.

like image 185
Willem Van Onsem Avatar answered Jan 29 '26 12:01

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!