简体   繁体   中英

How can I check if two models equal each other in Django?

models.py:

class office_list(models.Model):
    name = models.CharField(max_length= 100)
    num_of_pax = models.IntegerField()

class tg_list(models.Model):
    name = models.CharField(max_length= 100)
    num_of_pax = models.IntegerField()

How can I check that the office_list name equals to the tg_list name? I want to check if any of the office_list.name == any of the tg_list.name

if you want

any of the office_list.name == any of the tg_list.name

you can do simple query with exists :

names = tg_list.objects.values_list('name', flat=True)
office_list.objects.filter(name__in=names).exists()

From the Django doc :

To compare two model instances, just use the standard Python comparison operator, the double equals sign: == . Behind the scenes, that compares the primary key values of two models.

or :

Youu can do with __eq__ in python too:

See python docs too.

The accepted answer requires an DB call, and specifically checks 1 field. In a more realistic scenario, you would be checking some subset of fields to be equal - likely ignoring PK's, creation timestamps, amongst other things.

A more robust solution would be something like:

class MyModel(Model):
    some_field_that_is_irrelevant_to_equivalence = models.CharField()
    some_char_field = models.CharField()
    some_integer_field = models.IntegerField()

    _equivalent_if_fields_equal = (
        'some_char_field',
        'some_integer_field',
    )

    def is_equivalent(self, other: 'MyModel') -> bool:
        """Returns True if the provided `other` instance of MyModel
        is effectively equivalent to self.

        Keyword Arguments:
        -- other: The other MyModel to compare this self to
        """
        for field in self._equivalent_if_fields_equal:
            try:
                if getattr(self, field) != getattr(other, field):
                    return False
            except AttributeError:
                raise AttributeError(f"All fields should be present on both instances. `{field}` is missing.")
        return True

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