在Django rest中添加连接模型中的字段

时间:2016-03-22 11:07:10

标签: python django django-rest-framework

我是django rest framework的新手。

我有一个模型chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) {// this code can modify NewTab page, and will modify only it }); Client

Project

在我的项目/序列化器中:

class Client(models.Model):
    name = models.CharField(max_length=100)


class Project(models.Model):
    client = models.ForeignKey(Client)
    name = models.CharField(max_length=100)

在我的项目/观点中:

class ProjectSerializer(CoreHyperlinkedModelSerializer):
    class Meta:
        model = Task
        fields = ('url', 'id', 'name')

我希望能够在ProjectSerializer中添加Client主键,因此在api浏览器视图中创建时,我可以 添加新数据。

2 个答案:

答案 0 :(得分:1)

您必须将其添加到Project Serializer中。如果将外键添加到字段中,它将为您提供主键。

rename_files() {
    title="${1##*${2} - }"
    exttitle="${2}"
    iters=0
    numfiles=$(ls -l "$1/"*.* | wc -l)
    for filename in "$1/"*.*; do
      new_path="${todir}${exttitle}/${title}.${filename##*.}"
      iters=_$(( ++i ))
      # extract $path without dot + extension
      new_path_basename=${new_path%*.*};
      # Extract extension from $path
      ext=${new_path##*.};
      if [ "$numfiles" -eq 1 ]; then
          iters=""
      fi
      case "${filename##*.}" in txt|rtf|pages|numbers|keynote|doc|docx|xls|ppt|pdf)
        mkdir -p -m 777 "${todir}${exttitle}"
        echo "moving $filename -> ${new_path_basename}${iters}.${ext}"
        # Add ${iters} before extension
        mv "${filename}" "${new_path_basename}${iters}.${ext}"
      ;;
      esac
    done
}

rename_category() {
  for path in "${fromdir}${1}"*; do
    rename_files "$path" "$1"
  done
}

rename_category DOC

或者,如果要在Project serializer中修改客户端视图,可以使用嵌套序列化。

class ProjectSerializer(CoreHyperlinkedModelSerializer):
    class Meta:
        model = Task
        fields = ('url', 'id', 'name', 'client', )

答案 1 :(得分:1)

这可能不是你应该做的事情,但是为了获得主键,你可以使用PrimaryKeyRelatedField

class ProjectSerializer(...):
    client = serializers.PrimaryKeyRelatedField(queryset=Client.objects.all)

    class Meta:
        model = Project
        fields = ('url', 'id', 'name', 'client', )