简体   繁体   中英

Have a model with an object I want to connect to two other models (Django)

I need the "eventList" to connect to both "Event" and "customEvent". I'm not sure how to declare the ManyToManyFields on it. What I have right now is:

    eventList = models.ManyToManyField(Event, blank="TRUE", null="TRUE", related_name='event_set+')
    eventList = models.ManyToManyField(customEvent, blank="TRUE", null="TRUE")

I don't think this works because it just reassigns eventList on the second line. How would I get this accomplished?

You can do this:

class EventConnect(models.Model)
    events = models.ForeignKey(MyEvent)
    eventList = models.ForeignKey(Event, blank="true", null="true", related_name='event_set+')
    customEventList = models.ForeignKey(customEvent, blank="true", null="true", related_name='customevent_set+')

    class Meta:
        unique_together('events', 'Event', 'customEvent')

class MyEvent(models.Model):
    #rest of the fields..

Note that ForeignKey is sufficient in the intermediary table. You cannot assign multiple many to many against the same model field. (like assigning 2 different values to the same database column - which is not possible unless you manage the keys yourself.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM