0

I have a model say Club where we have fields like:

manager = models.ForeignKey(Users, related_name="return_manager", on_delete=models.CASCADE)
members = models.ManyToManyField(Users, related_name="return_members", blank=True)

Now I want to create a drop down in a form where I can add both the manager and members to it. I tried making two requests for Club.objects.filter(pk=mypk).members.all() and Club.objects.filter(pk=mypk).manager. I tried chain function and using '| ' operator but none worked. I think the manager is a single User and not a queryset, that is what the main problem is. Any workarounds?

markwalker_
  • 12,078
  • 7
  • 62
  • 99
Akshay Bhasin
  • 167
  • 2
  • 3
  • 11

2 Answers2

0

One possible way getting all of the information together involves modifying your form choices.

In your view you would need to pass the choices along as context to your form.

def my_view(request, club_pk):
    context = {}
    context.update({
        "manager": Club.objects.get(pk=club_pk).manager,
        "members": Club.objects.get(pk=club_pk).members.all()
    }
    form = MyForm(request.POST or None, request=request, context=context)

In your form, you would need to modify the __init__ method to update your choices like so:

class MyForm(forms.Form):
    all_club_members = forms.ChoiceField('Manager + Members', required=True)

    def __init__(self, *args, **kwargs):
        self.context = kwargs.pop('context', None)

        super(MyForm, self).__init__(*args, **kwargs)

        manager_tuple = [(self.context['manager'].id, self.context['manager'].display_name)]
        members_tuples = [(member.id, member.display_name) for member in self.context['members']
        self.fields['all_club_members'].choices = manager_tuple + members_tuples
knelson
  • 126
  • 1
  • 6
0

Try this:

manager = [Club.objects.filter(pk=mypk).manager]
members = Club.objects.filter(pk=mypk).members.all()
userlist = list(manager) + list(members)
return Users.objects.filter(pk__in=userlist)

Should create a queryset of all users

Written
  • 635
  • 4
  • 12
  • I have to return a queryset only. Am overriding the get_queryset method. – Akshay Bhasin Jun 28 '16 at 14:57
  • You now have a list of users, you can return a query set of all the user id's using `Users.objects.filter(pk__in=userlist)` http://stackoverflow.com/questions/1058135/django-convert-a-list-back-to-a-queryset – Written Jun 28 '16 at 15:02