首页 \ 问答 \ Django Rest Serializer:反向关系(Django Rest Serializer: Reverse relationships)

Django Rest Serializer:反向关系(Django Rest Serializer: Reverse relationships)

免责声明:我正在学习django,因为我将它应用于我继承的数据库/ PHP应用程序。 数据库有点混乱,没有外键约束,命名也不一致。 我不想触摸或重做数据库上的任何内容,因为我根本不想使用遗留应用程序。

Stack:Python 2.7。 Django 1.5,Django Rest Framework

问题是我有一个关系,其中有一个具有多个代码的Idea。 代码表有想法的外键(teaser_id),所以我们有类似的东西

**Tickers**
id teaser_id 
1  1
2  1
3  1
4  2
4  2 

**Ideas**
id
1
2

我让django从数据库生成模型,但没有FK约束,它没有正确生成所有关系。 所以这里有模型配置:

class Tickers(models.Model):
    id = models.IntegerField(primary_key=True)

    # I changed to this
    teaser_id = models.ForeignKey(Idea)
    # From        
    # teaser_id = models.IntegerField(null=True, blank=True)

    ticker = models.CharField(max_length=135L, blank=True)
    date_added = models.CharField(max_length=135L, blank=True)
    class Meta:
        db_table = 'teaser_tickers'


class Idea(models.Model):
    id = models.IntegerField(primary_key=True)
    industry_id = models.IntegerField()
    post_type = models.CharField(max_length=45L)

    class Meta:
        db_table = 'idea'

这是我的序列化器

class TickerSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = myModels.Tickers
        fields = (
            'id'
            ,'teaser_id'
            ,'ticker'
        )

class IdeaSerializer(serializers.HyperlinkedModelSerializer):
    user = UserSerializer(many=False, read_only=True)
    ticker = TickerSerializer(many=True, read_only=True, )
    teaser = myFields.TeaserField(teaser_length=200, original_field='content')

    class Meta:
        model = myModels.Idea
        fields = (
            'id'
            , 'title'
            , 'date_added'
            , 'user'
            , 'teaser'
            , 'ticker'
        )

我希望Ideas Resource将代码作为子节点集返回。

REST请求用于Idea,其中代码是子元素。 所以我得到一个例外,即故障定义没有在想法中定义。 很好 - 但我只是猜测如何在这一点上设置它 - 我通过文档和源代码进行了抨击 - 但希望有人可以帮助我。

谢谢


Disclaimer: I am learning django as I apply it to a database / PHP app i inherited. The database is a bit of a mess, with no foreign key constrains, and inconsistent naming. I do not want to touch or redo anything on the database because I don't want to mes with the legacy application at all.

Stack: Python 2.7. Django 1.5, Django Rest Framework

The problem is that I have a relationship where there is an Idea that has multiple Tickers. The tickers table has the foreign key to the ideas (teaser_id) so that we have something like

**Tickers**
id teaser_id 
1  1
2  1
3  1
4  2
4  2 

**Ideas**
id
1
2

I had django generate the model from the database, but without the FK Constraints it didn't generate all the relationships properly. So here is haw the models are configured:

class Tickers(models.Model):
    id = models.IntegerField(primary_key=True)

    # I changed to this
    teaser_id = models.ForeignKey(Idea)
    # From        
    # teaser_id = models.IntegerField(null=True, blank=True)

    ticker = models.CharField(max_length=135L, blank=True)
    date_added = models.CharField(max_length=135L, blank=True)
    class Meta:
        db_table = 'teaser_tickers'


class Idea(models.Model):
    id = models.IntegerField(primary_key=True)
    industry_id = models.IntegerField()
    post_type = models.CharField(max_length=45L)

    class Meta:
        db_table = 'idea'

Here are my serializers

class TickerSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = myModels.Tickers
        fields = (
            'id'
            ,'teaser_id'
            ,'ticker'
        )

class IdeaSerializer(serializers.HyperlinkedModelSerializer):
    user = UserSerializer(many=False, read_only=True)
    ticker = TickerSerializer(many=True, read_only=True, )
    teaser = myFields.TeaserField(teaser_length=200, original_field='content')

    class Meta:
        model = myModels.Idea
        fields = (
            'id'
            , 'title'
            , 'date_added'
            , 'user'
            , 'teaser'
            , 'ticker'
        )

I want the Ideas Resource to return the tickers as a child node set.

The REST request is for the Idea where the tickers is a child element. So I am getting an exception that ticker isn't defined in idea. Fine get that - but I am just guessing on how to set this up at this point - I am sludging through documentation and source - but was hoping someone could help me out.

THank you


原文:https://stackoverflow.com/questions/19326327
更新时间:2022-09-12 12:09

最满意答案

这是原始Expr类型的变体,它添加了变量( V )和let绑定( Let )。

data Expr = C Float | V String
          | Let [(String, Expr)] Expr
          | Expr :+ Expr | Expr :- Expr
          | Expr :* Expr | Expr :/ Expr

为了帮助编写evaluate ,您可能希望从一个执行变量替换的函数开始:

data Expr = C Float | V String
          | Let [(String, Expr)] Expr
          | Expr :+ Expr | Expr :- Expr
          | Expr :* Expr | Expr :/ Expr
            deriving Show

-- | @sub var value e@ replaces variables named @var@ with the value @value@
-- wherever anywhere that variable occurs in expression @e@.
sub :: String -> Expr -> Expr -> Expr

-- "let x = y in x" = y
sub v1 value (V v2) | v1 == v2 = value

-- "let x = y in z" = z
sub _ _ e@(V _) = e

-- Constants are unaffected
sub _ _ c@(C _) = c

-- For operators, apply @sub a b@ recursively to the operands.
sub a b (e1 :+ e2) = (sub a b e1) :+ (sub a b e2)
sub a b (e1 :- e2) = (sub a b e1) :- (sub a b e2)
sub a b (e1 :* e2) = (sub a b e1) :* (sub a b e2)
sub a b (e1 :/ e2) = (sub a b e1) :/ (sub a b e2)

-- The variable is shadowed by a let binding, so only substitute
-- into the bindings, and leave the body expression unmodified.
sub a b (Let bindings e) | bindingsContains a bindings =
    Let (subIntoBindings a b bindings) e

-- Apply @sub a b@ recursively to the body of the let expression.
sub a b (Let bindings body) =
    Let (subIntoBindings a b bindings) (sub a b body)

bindingsContains :: String -> [(String, Expr)] -> Bool
bindingsContains x bindings =
    Data.Maybe.isJust $ Data.List.find ((== x) . fst) bindings

subIntoBindings :: String -> Expr -> [(a, Expr)] -> [(a, Expr)]
subIntoBindings a b bindings = (fmap . fmap) (sub a b) bindings

Here's a variant of the original Expr type that adds variables (V) and let bindings (Let).

data Expr = C Float | V String
          | Let [(String, Expr)] Expr
          | Expr :+ Expr | Expr :- Expr
          | Expr :* Expr | Expr :/ Expr

To help write evaluate, you may want to start with a function that does variable substitution:

data Expr = C Float | V String
          | Let [(String, Expr)] Expr
          | Expr :+ Expr | Expr :- Expr
          | Expr :* Expr | Expr :/ Expr
            deriving Show

-- | @sub var value e@ replaces variables named @var@ with the value @value@
-- wherever anywhere that variable occurs in expression @e@.
sub :: String -> Expr -> Expr -> Expr

-- "let x = y in x" = y
sub v1 value (V v2) | v1 == v2 = value

-- "let x = y in z" = z
sub _ _ e@(V _) = e

-- Constants are unaffected
sub _ _ c@(C _) = c

-- For operators, apply @sub a b@ recursively to the operands.
sub a b (e1 :+ e2) = (sub a b e1) :+ (sub a b e2)
sub a b (e1 :- e2) = (sub a b e1) :- (sub a b e2)
sub a b (e1 :* e2) = (sub a b e1) :* (sub a b e2)
sub a b (e1 :/ e2) = (sub a b e1) :/ (sub a b e2)

-- The variable is shadowed by a let binding, so only substitute
-- into the bindings, and leave the body expression unmodified.
sub a b (Let bindings e) | bindingsContains a bindings =
    Let (subIntoBindings a b bindings) e

-- Apply @sub a b@ recursively to the body of the let expression.
sub a b (Let bindings body) =
    Let (subIntoBindings a b bindings) (sub a b body)

bindingsContains :: String -> [(String, Expr)] -> Bool
bindingsContains x bindings =
    Data.Maybe.isJust $ Data.List.find ((== x) . fst) bindings

subIntoBindings :: String -> Expr -> [(a, Expr)] -> [(a, Expr)]
subIntoBindings a b bindings = (fmap . fmap) (sub a b) bindings

相关问答

更多
  • 看看源代码,我们有iadd :: (IsInteger c, ABinOp ab (vc)) => a -> b -> CodeGenFunction r (vc) 。 然后, iadd的前两个参数必须是iadd成员 - 但你已经知道了这一点,GHC告诉你。 我怀疑,我认为(v0 c0)不是问题。 从源头看, ABinOp定义为class ABinOp abc | ab -> c where class ABinOp abc | ab -> c where 。 最后一个类型参数c由给定任意两个输入参数的类型 ...
  • 它不是Prelude的Enum实例(请参阅文件顶部附近的import Prelude hiding (Enum(..)) )。 它是Graphics.UI.SDL.Utilities的Enum实例,它带有第二个参数: class Enum a b | a -> b where succ :: a -> a pred :: a -> a toEnum :: b -> a fromEnum :: a -> b enumFromTo :: a -> a -> [a] 与前奏中的定义相比: c ...
  • 如果您想通过ghci使变量类型脱机,则必须输入 :t 表达式 如果你想在ghci中创建变量,你必须使用let而不使用'in'(如monad的表示法,我不知道你是否已经看过它们): let var = expr 如果你自己检查一下,你应该能够更容易地为你的考试记住它。 (祝你好运;)) If you want to get types of variables offline with ghci you have to type :t expression if you want to create vari ...
  • 这里的问题是(从错误消息中推导出) priceOf返回一个Int而0.95 * 8 * 2具有多态类型Fractional a => a ,并且shouldBe强制这些类型相同。 但是Int不是Fractional类型,所以你会得到“没有Fractional Int实例”。 如何解决这个问题: 使priceOf返回Fractional类型,例如Double或 根据您的要求,使用round , floor或ceiling之一将0.95 * 8 * 2转换为Int 。 The problem here is t ...
  • 我真的不明白你要做什么,但我会说这个。 类型主要用于对值进行分类。 构建大量的类型级别信息,使用Proxy在值级别擦除它,然后尝试使用类来恢复它以在类型上进行模式匹配会导致复杂的代码(如您所见)并且不会在安全性或简洁性方面真的给你带来任何东西。 把事情简单化。 我的建议是更仔细地考虑您的API客户提前知道哪些信息 - 这是类型级的东西 - 以及客户想要动态构建的内容。 使用类型级别的东西来对值级别的东西进行分类。 在这种情况下,您的用户将提前知道他们的架构 - 模型的各个维度 - 但他们通常不会知道他们将查 ...
  • 你可以使用,例如, data BinOp = Add | Mul data UnaryOp = Sin | Cos data Expr = Num Double | Binary BinOp Expr Expr | Unary UnaryOp Expr YMMV关于这是否更简单。 You can use, e.g., data BinOp = Add | Mul data UnaryOp = Sin | Cos data Expr = Num Double | Binary Bin ...
  • 几乎就是这样,但有一些轻微的语法调整,所以你说的是GHC的语言。 data Expr = Numb Int | Add Expr Expr | Diff Expr Expr | Mult Expr Expr eval :: Expr -> Int eval (Numb x) = x eval (Add e e') = eval e + eval e' eval (Diff e e') = eval e - eval e' eval (Mult e e') = eval e * eval e' 在ghci ...
  • 我不是该库的专家,但似乎是为了允许用户定义的装饰而设计的。 这是因为所有主要数据类型都通过NodeInfo进行参数化, NodeInfo是标准注释(仅携带位置和名称信息)。 例如图书馆提供 type CTranslUnit = CTranslationUnit NodeInfo 它允许您定义 type MyTransUnit = CTranslationUnit MyNodeInfo data MyNodeInfo = MNI NodeInfo AdditionalStuffHere 所以按照你的意愿装 ...
  • 这是原始Expr类型的变体,它添加了变量( V )和let绑定( Let )。 data Expr = C Float | V String | Let [(String, Expr)] Expr | Expr :+ Expr | Expr :- Expr | Expr :* Expr | Expr :/ Expr 为了帮助编写evaluate ,您可能希望从一个执行变量替换的函数开始: data Expr = C Float | V Strin ...
  • 如果你还派生了一个Enum实例,你可以使用fromEnum :: Enum a => a -> Int和toEnum :: Enum a => Int -> a在你的数据类型和整数之间进行转换,这些数据类型和整数对应于它们在数据定义中的位置。 由于您在第0个位置上有Zero ,所以这就是您想要进入整数和整数的正确值。 但你还应该考虑: addNumber Three Two的结果是什么? 这里没有正确的价值,因为你对数字的定义不会达到五。 无论您设置了哪个上限,都会有一个“部分”函数,该函数在其域中的某些值 ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)