我正在尝试将管理应用中的外键选项限制为特定用户(我尝试限制的字段称为学校)。这就是我的代码的样子 - 不幸的是,当我尝试编辑学生时(通过点击他们的名字),有两个问题(如下所述)。
1.学校的默认值是 -
2.当我从下拉菜单中选择合适的学校并尝试保存时,我会在校园里收到错误
选择有效的选择。这种选择不是可用的选择之一 选择。
这就是它的样子
class modelStudentAdmin(admin.ModelAdmin):
def get_queryset(self, request):
qs = super(modelStudentAdmin, self).get_queryset(request)
if request.user.is_superuser:
return qs
else:
schoolInstance = modelSchool.objects.get(user=request.user)
qs = modelStudent.objects.filter(school=schoolInstance)
return qs
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if request.user.is_superuser:
return super(modelStudentAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
#Not superuser only staff
if db_field.name == 'school':
t = modelSchool.objects.filter(user=request.user).values_list("school_name",flat=True)
kwargs['queryset'] = t
return super(modelStudentAdmin,self).formfield_for_foreignkey(db_field, request, **kwargs)
现在,如果我删除方法
def formfield_for_foreignkey(self, db_field, request, **kwargs):
一切正常但我不能限制外键。关于我可能做错什么的任何建议?
答案 0 :(得分:1)
尝试替换
@Getter
@Setter
@Entity
@EqualsAndHashCode
@Table(name = "produto")
@IdClass(ProdutoId.class)
public class Produto implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id_produto")
private Long idProduto;
@Id
@Column(name = "oficina", insertable = false, updatable = false)
private Long idOficina;
@ManyToOne
@JoinColumn(name = "oficina")
private Oficina oficina;
}
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
@Data
public class ProdutoId implements Serializable {
public Long idProduto;
public Long idOficina;
}
@Repository
public interface ProdutoRepository extends JpaRepository<Produto, ProdutoId> {}
用这个
import org.springframework.core.convert.converter.Converter;
public class BuildingIdToBuildingConverter implements Converter<String, Building> {
private BuildingService buildingService;
public BuildingIdToBuildingConverter(BuildingService buildingService) {
this.buildingService = buildingService;
}
@Override
public Building convert (String id) {
return buildingService.getBuilding(id);
}
}
您不需要value_list您的查询集。