Vin
Vin

Reputation: 986

Getting an error while using bulk_create() method of Django

I'm trying to bulk create some entries using bulk_create() method of Django in the DB table. On the final step where I'm passing the created list over there getting an error TypeError: int() argument must be a string, a bytes-like object or a number, not 'tuple' and due to this obviously no records are getting saved.

Below is the code through which I'm trying to save the records in the DB table.

Class method

@classmethod
def mark_all_added(cls, id: int, spec_id: int) -> None:
    spec_ids = set(
        cls.objects.filter(spec_id=spec_id)
        .values_list("id")
    )

    through_objects = [
        cls.added_by.through(id=id, spec_id=sid)
        for sid in spec_ids
    ]

    cls.added_by.through.objects.bulk_create(through_objects) # getting error on this line

Could someone please help in highlighting my mistake or tell me how to resolve this issue while saving bulk records. I know I have a done a silly mistake but am unable to trace it. Any kind of would be much appreciated. Thanks in advance.

Upvotes: 1

Views: 926

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476659

You need to make a flat list of 'id's, not a QuerySet of singleton tuples, by specifying flat=True in the .values_list(…) method [Django-doc], so:

@classmethod
def mark_all_added(cls, id: int, spec_id: int) -> None:
    spec_ids = set(
        cls.objects.filter(spec_id=spec_id)
        .values_list('id', flat=True)  # ← use flat=True
    )
    # …

Upvotes: 1

Related Questions