搜索属于已登录用户业务的客户?

huangapple go评论53阅读模式
英文:

Search Customers that are part of the logged on User's Business?

问题

我目前的代码如下,在我的views.py中我无法弄清楚如何设置我的搜索功能。所有其他函数都能正常工作。

models.py

class User(AbstractUser):
    "用户可以是员工或客户"

class Business(models.Model):
    business = models.CharField(max_length=50)

class BusinessOwner(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, null=True )
    business = models.ForeignKey(Business, on_delete=models.CASCADE, null=True)

class Customer(models.Model):
    "客户特定信息"
    user = models.OneToOneField(User, on_delete=models.CASCADE, null=True )
    business = models.ForeignKey(Business, on_delete=models.CASCADE, null=True)

class Employee(models.Model):
    "员工特定信息"
    user = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
    business = models.ForeignKey(Business, on_delete=models.CASCADE, null=True, blank=True)

forms.py

class UserForm(UserCreationForm):
    class Meta:
        model = User
        fields = ("username", "email", "password1", "password2", "first_name", "last_name",)

class BusinessOwnerForm(forms.ModelForm):
    ... 没有字段

class EmployeeForm(forms.ModelForm):
    ... 没有字段

class CustomerForm(forms.ModelForm):
    ... 没有字段

class BusinessForm(forms.ModelForm):
    class Meta:
        model = Business
        fields = ("business",)

views.py(用户创建流程)

...(省略其他内容)

def searchUsers(request):
    ...(省略其他内容)

def employeeCreation(request):
    "创建员工"
    ...(省略其他内容)

def customerCreation(request):
    "创建客户"
    ...(省略其他内容)

...(省略其他内容)

search_users.html
英文:

The code I currently have is this, in my views.py I can't figure out how to set up my search function. All other functions work.

models.py

class User(AbstractUser):
    """User can be Employee or Customer"""

class Business(models.Model):
    business = models.CharField(max_length=50)

class BusinessOwner(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, null=True )
    business = models.ForeignKey(Business, on_delete=models.CASCADE, null=True)

class Customer(models.Model):
    """ Customer-specific information """
    user = models.OneToOneField(User, on_delete=models.CASCADE, null=True )
    business = models.ForeignKey(Business, on_delete=models.CASCADE, null=True)

class Employee(models.Model):
    """ Employee-specific information """
    user = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
    business = models.ForeignKey(Business,  on_delete=models.CASCADE, null=True, blank=True)`

forms.py

class UserForm(UserCreationForm):
	class Meta:
		model = User
		fields = ( "username", "email", "password1", "password2", "first_name", "last_name", )


class BusinessOwnerForm(forms.ModelForm):
. . . no fields
class EmployeeForm(forms.ModelForm):
. . . no fields

class CustomerForm(forms.ModelForm):
. . . no fields

class BusinessForm(forms.ModelForm):
	class Meta:
		model = Business
		fields = ( "business",  )

views.py (user creation process)

def searchUsers(request):
	qs_owned_businesses = BusinessOwner.objects.filter(user = request.user).values('business_id')
	qs_biz_customers = Customer.objects.filter(business_id__in=qs_owned_businesses)
	if request.method == "GET":
		query = request.GET.get('search')
		if query == '':
			query = 'None'
	results = User.objects.filter(username__icontains=query, id__in=qs_biz_customers)
	return render(request, 'search_users.html', {'query': query, 'results': results})
	
	


#example of hows employees and customers are created in my views:
def employeeCreation(request):
	"""Creates an Employee"""
	if request.method == "POST":
		employee_form = EmployeeForm(request.POST)
		user_creation_form = UserForm(request.POST)
		if (user_creation_form.is_valid() and employee_form.is_valid()):
			employee_form.instance.business = request.user.businessowner.business
			new_user = user_creation_form.save(commit=False)
			employee_form.instance.user = new_user
			user_creation_form.save()
			employee_form.save()
			messages.success(request, "You Have Created An Employee" )
			return redirect("user-homepage")
		else:
			messages.error(request, "Try creating an Employee Again something went wrong.")
	employee_form = EmployeeForm()
	user_creation_form = UserForm()
	return render (request, "registration/employee_creation.html", 
		context={"user_creation_form": user_creation_form, 
	   			"employee_form": employee_form,
					})


def customerCreation(request):
. . . functions is exactly the same as employee creation just for a customer. The Business owner's business is used as a starting point to build employees off of. I didn't incldue that view because it's not necessary for this and stack overflow limits how much code I put here.


search_users.html

{% if results %}
<h1> you Searched for {{ query }} . . </h1>

    {% for x in results %}
        {{ x }}&lt;p&gt;&lt;/p&gt;
    {% endfor %}

{%endif %}```

I have tried using Q, icontain ,.filter() and django-filter, but this is a tricky search criteria that I can't get to work.

navbar search feature:

       &lt;form action=&quot;{% url &#39;search-users&#39; %}&quot; class=&quot;form-inline&quot; method=&quot;get&quot;&gt;
      &lt;div class=&quot;form-group mx-sm-3 mb-2&quot;&gt;
      &lt;label for=&quot;&quot; class=&quot;sr-only&quot;&gt;search&lt;/label&gt;
      &lt;input name=&quot;search&quot; type=&quot;&quot; class=&quot;form-control&quot; id=&quot;&quot; placeholder=&quot;Keyword&quot;&gt;
      &lt;/div&gt;
     &lt;button type=&quot;submit&quot; class=&quot;btn btn-success btn-lg mb-2&quot;&gt;Search&lt;/button&gt;
&lt;/form&gt;```

</details>


# 答案1
**得分**: 0

让我们将这分解成任务。我使用`values()`来限制请求仅包括我们感兴趣的内容,因为我可以使用该结果进一步筛选。

    # 首先,您要获取当前登录用户拥有的所有企业
    # (目前他们只能拥有一个,所以您可以使用`get`而不是`filter`,
    # 但您以后可能会更改,这种方法仍然有效)
    qs_owned_businesses = BusinessOwner.objects.filter(user=request.user).values('business_id')
    
    # 接下来,您要获取这些企业的所有客户
    qs_biz_customers = Customer.objects.filter(business_id__in=qs_owned_businesses).values('user_id')
    
    # 最后,您要根据您的表单字段进一步筛选这些客户
    # 请记住,`icontains`条件需要引用一个字段
    # 这里我们正在查看用户名,但您可能使用姓氏或其他内容。
    results = User.objects.filter(username__icontains=query, id__in=qs_biz_customers)

`results`现在应该是一个用户列表,您可以在模板中循环遍历以显示姓名、用户名等信息。

<details>
<summary>英文:</summary>

Let&#39;s break this down into tasks. I&#39;m using values() to limit the request to what we&#39;re interested in, as I can then use that result to filter further.

    #First you want to get all the businesses the logged in user owns
    #(Currently they can only own one, so you could use get rather than filter,
    #but you might change that later and this approach will still work)
    qs_owned_businesses = BusinessOwner.objects.filter(user = request.user).values(&#39;business_id&#39;)
    
    #next you want to get all the customers of those businesses
    qs_biz_customers = Customer.objects.filter(business_id__in= qs_owned_businesses).values(&#39;user_id&#39;)
    
    #finally you want to filter those customers further based on your form field
    #remember, the icontains criteria needs to refer to a field
    #here we&#39;re looking at username, but you might use last_name or something else.
    results = User.objects.filter(username__icontains=query, id__in=qs_biz_customers)

`results` should now be a list of users you can cycle through in your template to show names, usernames etc.



</details>



huangapple
  • 本文由 发表于 2023年6月1日 10:31:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76378323.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定