Domanda

I'm trying to write a function that would store a concatenated sting of several fields, including some stored in a relationship table of a M2M relationship. Here is the code:

class substance(models.Model):
  name = models.Charfield()
  ...


class rel_med_subs(models.Model):
  id_med = models.ForeignKey(medication, related_name='relation_med')
  id_subs = models.ForeignKey(substance, related_name='relation_subs')
  order = models.IntegerField()
  strength = models.FloatField(null=True, blank=True)
  strength_unit = models.ForeignKey(units)


class medication(models.Model):
  name = models.Charfield()
  substance = models.ManyToManyField(substance, through='rel_med_subs')
  autogenerated = models.CharField(blank=False, default='')
  ...

  def save(self, force_insert=False, force_update=False):
    self.autogenerated = u'%s' % (' '.join[(u'%s %s'(s.name, s.strength) for s in self.rel_med_subs.order_by('order')])
    self(medication,self).save(force_insert,force_update

When I only ask for the name, the function works fine, but if I try to bring attributes from the relationship table, django complains that strength is not part of the substance model.

How can I get attributes from the relationship into my autogenerated field?

Thanks!

È stato utile?

Soluzione

The problem is that the name and strength attributes belong to different objects (strength belongs to rel_med_subs, name to substance)! You can't refer to both of them through the (s.name, s.strength) for s in self.rel_med_subs.order_by('order') comprehension - the s can only have name or strength.

It seems that the rel_med_subs attribute is a relation manager for objects of type substance and not of type rel_med_subs. Check the attributes of medication using dir to see which is the name of the manager for rel_med_subs (probably something like rel_med_subs_set -- I really can't remember it and always check it with dir. However be assured that medication will have two reverse relation attributes: One for the Many 2 Many relation with substance and one with the One 2 Many with rel_med_subs. After you find the correct reverse manager then you can use s.id_subs.name and s.strength.

Also please capitalize your class names and use corrent naming (rel_med_subs should be named MedicineSubstanceRelation) !

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top