0

This is my code:

PostModels = {
    'dPost': DPost,
    'sPost': SPost,
    'rPost': RPostModel,
}

for postType, Post in PostModels.items():
    try:
        post = Post.objects.get(pk=pk)
    except:
        pass
    else:
        return RPostModel.objects.filter(postType=post)

When I do post = Post.objects.get(pk=pk), Post is the variable Post in the for loop. So on first loop, it searches the objects in DPost, on the next loop it searchs SPost etc. However, when it reaches the return statement, it gives an error saying:

django.core.exceptions.FieldError:
Cannot resolve keyword 'postType' into field.
Choices are: createdAt, dPost, dPost_id, sPost, sPost_id, rPost, rPost_id

How do I make postType equal to what the postType variable is equal to? In other words, in the loop, how can I get my return statement to be these statements:

return RPostModel.objects.filter(dPost=post)
return RPostModel.objects.filter(sPost=post)
return RPostModel.objects.filter(rPost=post)

rather than this:

return RPostModel.objects.filter(postType=post)
SilentDev
  • 20,997
  • 28
  • 111
  • 214

1 Answers1

2

Try this:

for postType, Post in PostModels.items():

    try:
        post = Post.objects.get(pk=pk)
    except:
        pass
    else:
        kwargs = {postType: post}
        return RPostModel.objects.filter(**kwargs)
masnun
  • 11,635
  • 4
  • 39
  • 50
  • Just to verify, should `kwargs = {postType: Post}` or `kwargs = {postType: post}` where `post = Post.objects.get(pk=pk)`? – SilentDev Dec 12 '15 at 02:13
  • Sorry my bad, yes, `post` - the one you want to pass to the `RPostModel.objects.filter` – masnun Dec 12 '15 at 02:17
  • Okay thanks. Would you be able to quickly explain what's going on, as I am fairly new to python's `**` expression. What exactly is it doing there? Because I just opened up Python and did `kwargs = {'a':1}` and then `print(**kwargs)` and it gives an error. How exactly does it work in the return statement even when `**kwargs` is an error for me? – SilentDev Dec 12 '15 at 02:25
  • This should help: http://stackoverflow.com/questions/1769403/understanding-kwargs-in-python – masnun Dec 12 '15 at 02:28
  • In our case however, `**kwargs` serves the purpose converting string values to parameter names. We can not pass a string directly as the name of a parameter, so we put it as a key in a dictionary and pass the dictionary as `**kwargs` so the key is used as the parameter name here. – masnun Dec 12 '15 at 02:30