Alirezaarabi
Alirezaarabi

Reputation: 440

Working with many to many database in Django

I'm working with many to many databases in Django but I do not understand one piece of code.

what's the meaning of 5 in the below line of code:

areadata.objects.get(id = area_id).pub.add(mymodel.objects.get(id = restaurant_id),5)

If anyone knows that's meaning please explain it to me.

Upvotes: 1

Views: 127

Answers (1)

aaron
aaron

Reputation: 43128

It refers to the id of a row in the mymodel table.

  • areadata.objects.get(id=area_id).pub.add(mymodel.objects.get(id=restaurant_id), 5) calls
  • create_forward_many_to_many_manager.<locals>.ManyRelatedManager.
    def add(self, *objs, through_defaults=None)
    (with objs = (<mymodel: mymodel object (restaurant_id)>, 5)), which calls
  • create_forward_many_to_many_manager.<locals>.ManyRelatedManager.
    def _add_items(self, source_field_name, target_field_name, *objs, through_defaults=None), which calls
  • create_forward_many_to_many_manager.<locals>.ManyRelatedManager.
    def _get_target_ids(self, target_field_name, objs)

Truncated for brevity:

def _get_target_ids(self, target_field_name, objs):
    ...
    for obj in objs:
        if isinstance(obj, self.model):
            ...
            target_id = target_field.get_foreign_related_value(obj)[0]
            ...
            target_ids.add(target_id)
        elif isinstance(obj, Model):
            raise TypeError(...)
        else:
            target_ids.add(obj)
    return target_ids

Since 5 is neither an instance of mymodel nor Model, it is considered as an id of mymodel.

The resulting target_ids is {restaurant_id, 5}.

Upvotes: 1

Related Questions