[Fixed]-How to copy an object's field to another object's field

1👍

I think it would be much cleaner to store kwargs.get(‘instance’) in a variable and then work with that. This will also get rid of your error. Then tags have to be assigned after the activity object is created.

if kwargs.get('created', False):
    news_obj = kwargs.get('instance')
    if not news_obj:
        return
    actor_type = ContentType.objects.get_for_model(news_obj.user)
    actor_id = news_obj.user.id
    target_type = ContentType.objects.get_for_model(news_obj)
    target_id = news_obj.id
    ...
    ...
    tags = news_obj.tags.all()

    activity = Activity.objects.get_or_create(
        actor_type=actor_type,
        actor_id=actor_id,
        verb=verb,
        target_type=target_type,
        target_id=target_id,
        pub_date=pub_date
    )

    activity.tags.add(*tags)
    activity.save()

0👍

You should pay attention to the traceback you are getting. Even though you haven’t posted it here, it would be clear from it that the error is coming when you create the Activity, not when you read the tag from News. That’s because you can’t pass in data for a many-to-many field when you instantiate a model – because an object needs to be saved before you can assign M2M relations to it.

You should take the tags line out of the get_or_create call, and assign them afterwards.

Leave a comment