Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I dynamically create objects in django/python?

In my code I have many if/elif statements like this:

if type == "cat":
    vote = VoteCat (
        user = user,
        cat_id = thing_id )
    vote.save()
elif type == "dog":
    vote = VoteDog (
        user = user,
        dog_id = thing_id )
    vote.save()

What would be a good way to change my code to get rid of the if statements and instantiate the object I need dynamically? The code I am hoping I can write would accomplish the same as above but look more like this:

AnimalVote = get_animalvote_by_type(type)
AnimalVote.user = user
AnimalVote.assign_animal_id(thing_id)
AnimalVote.save()
like image 546
tedtoy Avatar asked Jun 28 '26 09:06

tedtoy


1 Answers

The simplest translation is:

types = dict('cat' = CatType, 'dog' = DogType)
newobj = types[type](user = user, cat_id = thing_id)

Obviously, this relies on the types taking the same parameters.

like image 83
Marcin Avatar answered Jun 29 '26 22:06

Marcin



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!