在此模型中,我有一个名为 UserTypes 的模型,我将User用作OneToOne字段,并且 UserTypes 模型与 User 模型内联。我创建此模型的目的是为用户提供状态,就像我们进行is_staff = True一样。 现在,我想在同一项目的另一个应用程序
中显示另一个名为Order的模型中显示其staff_status =“ Delivery Boy”的所有用户model.py(app1)
class UserTypes(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
staff_choices = (
('', ''),
('Admin', 'Admin'),
('Chef', 'Chef'),
('Delivery Boy', 'Delivery Boy'),
)
staff_status = models.CharField(max_length=15, choices=staff_choices, default=staff_choices[0][0])
def __str__(self):
return self.staff_status
model.py(app2)
class Order(models.Model):
name = models.CharField(max_length=60)
email = models.EmailField(max_length=60,default=None, blank=True)
mobile_no = models.CharField(max_length=13, default=None)
address = models.CharField(max_length=150)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status_choices = (
('In Queue', 'In Queue'),
('Processing', 'Processing'),
('Ready', 'Ready'),
('Delivered', 'Delivered'),
('Paid', 'Paid'),
('Cancelled', 'Cancelled'),
)
status = models.CharField(max_length=15, choices=status_choices,
default=status_choices[0][0])
total = models.DecimalField(max_digits=10, decimal_places=2,default=0)
class Meta:
ordering = ('created', )
def __str__(self):
return 'Order {}'.format(self.id)
def get_total(self):
return sum(item.get_cost() for item in self.items.all())
答案 0 :(得分:0)
在app2 models.py文件中添加一个字段以将用户类型存储在订单表中:
from app1.models import UserTypes
user = models.OneToOneField(UserTypes, on_delete=models.CASCADE)
将此代码添加到您的app2的admin.py文件中:
from app1.models import UserTypes
from .models import Order
class OrderAdmin(admin.ModelAdmin):
def get_form(self, request, obj=None, **kwargs):
form = super(OrderAdmin,self).get_form(request, obj,**kwargs)
# form class is created per request by modelform_factory function
# so it's safe to modify
# we modify the the queryset
form.base_fields['user'].queryset =
form.base_fields['user'].queryset.filter(staff_choices='Delivery Boy')
return form
admin.site.register(Order, OrderAdmin)