有没有办法在管理面板中选择显示的对象?
例如,我有两个用户,鸡蛋和aegon。如果我在用户交易下查看用户egg的配置文件,我可以看到所有交易,也可以看到aegon的交易。但我想过滤这只是为了显示egg的交易。模型:
class transaction(models.Model):
amount = models.IntegerField()
holding = models.ForeignKey(holding, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True)
def __str__(self):
return "amount: " + str(self.amount) + " - ip : " + str(self.holding.name) + " - user: " + str(self.user.username)
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
ip = models.IntegerField(default=0)
ingameName = models.CharField(max_length=50, default='NotSet')
userprofit = models.IntegerField(default=0)
user_transactions = models.ForeignKey(transaction, on_delete=models.CASCADE, blank=True, null=True)
管理员:
class UserProfileInline(admin.StackedInline):
model = UserProfile
can_delete = False
verbose_name_plural = 'profile'
class UserAdmin(UserAdmin):
inlines = (UserProfileInline, )
答案 0 :(得分:1)
是的,但您必须覆盖管理表单并过滤表单__init__()
方法中的选项。 __init__()
形式应该像这样(警告 - 未经测试的代码):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['user_transactions'].choices = transaction.objects.filter(user_id=user_id)
有关如何覆盖管理表单的信息,请查看文档:{{3}}