Множество различных посторонних объектов в качестве «ресурсов»

#django #orm

Вопрос:

Обновить

Вот чем я в итоге занялся:

 class Agenda(models.Model):  attendants = models.ManyToManyField("base.User", related_name="agendas", blank=True)  created_at = models.DateTimeField(auto_now_add=True)  date = models.DateTimeField(null=True)  text = models.TextField()   def get_restaurants(self):  return self.resources.instance_of(RestaurantResource)   def get_parking_lots(self):  return self.resources.instance_of(ParkingLotResource)   class Resource(PolymorphicModel):  agenda = models.ForeignKey(  Agenda, related_name="resources", on_delete=models.CASCADE  )  comment = models.TextField(null=True)   class RestaurantResource(Resource):  resource = models.ForeignKey(Restaurant, on_delete=models.CASCADE)   class ParkingLotResource(Resource):  resource = models.ForeignKey(ParkingLot, on_delete=models.CASCADE)   

Затем для каждого типа бизнеса, связанного с повесткой дня, я создаю свой конкретный ресурс (например, RestaurantResource). Итак, тогда я могу идти agenda_object.resources.all() .

Я все еще не доволен тобой. Это кажется излишним. Как и сейчас, мне нужно идти

 RestaurantResource.objects.create(resource=inv, agenda=agenda, comment="whatever") ParkingLotResource.objects.create(resource=pree, agenda=agenda, comment="somethi")  

Поэтому я должен отслеживать тип подключенного ресурса вместо того, чтобы просто перебирать ресурсы и создавать объекты.


Проблема

Итак, скажем, у меня есть модель, Повестка дня:

 class Agenda(models.Model):  ...  resource_comments = models.Field...  class ResourceComment(models.Model):  comment = models.TextField()  resource = models.ForeignKey... | GenericRelation  

Скажем, я хотела resource_comment быть одной или несколькими из нескольких других моделей, например.. Restaurant , PetrolStation , CarPark с комментарием.

Поэтому в повестке дня встречи мы, возможно, захотим поговорить о конкретном ресторане и паре близлежащих заправочных станций. Как бы то ни было, это удобный случай.

How would I go about this? Should I have a separate field for each..? That doesn’t feel quite right… like I don’t want

 class Agenda(models.Model):  ...  restaurants = models....  parking_lots = models..  petrol_stations = models..  ...  

I suppose I could have a model like…

 class Resource(models.Model):  resource_id = Int  resource_model = String # (e.g. Restaurant)   comment = String # (a comment pertaining to resource from having the agenda meeting)   

Kind of also feels off as I then have to manually get the objects.. Like

 get restaurants_in_agenda(self):  ids = self.filter(resource_model="Restaurant").value_list('ids')  return Restaurant.objects.filter(id__in=ids)  

Or, is this OK?

Another solution would be to make the Agenda the generic model, but I kind of don’t want this field on all the business models… because.. what do I do then with the resource comment?

 class Agenda(models.Model):  attendants = models.ManyToManyField("base.User", related_name="agendas", blank=True)  created_at = models.DateTimeField(auto_now_add=True)  date = models.DateTimeField(null=True)  text = models.TextField()   content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)  object_id = models.PositiveIntegerField()  content_object = GenericForeignKey("content_type", "object_id")  class OnAllBusinesses(models.Model):  ...  agendas = GenericRelation(Agenda)  

Something else I’ve thought about is «through» so,

 class Agenda(models.Model):  restaurants = models.ManyToManyField(  "restaurant",  through="AgendaResource",  through_fields=("agenda", "restaurant"))  ...  class AgendaResource(models.Model):  restaurant = models.ForeignKey(...)  agenda = models.ForeignKey(...)  comment = models.TextField()  ...  

Но потом у меня снова есть по одному для каждого вида бизнеса…

Спасибо за любую помощь.